How to check if a string starts with one of several prefixes? How to check if a string starts with one of several prefixes? java java

How to check if a string starts with one of several prefixes?


Do you mean this:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || ...)

Or you could use regular expression:

if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*"))


Besides the solutions presented already, you could use the Apache Commons Lang library:

if(StringUtils.startsWithAny(newStr4, new String[] {"Mon","Tues",...})) {  //whatever}

Update: the introduction of varargs at some point makes the call simpler now:

StringUtils.startsWithAny(newStr4, "Mon", "Tues",...)


No one mentioned Stream so far, so here it is:

if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))