I have an array and I want to search it for strings which start with “test” (for example); what is the most efficient way to search for these set prefixes? Regular expressions or if statements?
Regex:
boolean found = false;
for (String line: ArrayList){
Pattern pattern =
Pattern.compile("^test"); //regex
Matcher matcher =
pattern.matcher(line);
while (matcher.find()) {
found = true;
}
if(found){
doSomething();
}
}
}
if Statement:
for (String line : ArrayList) {
if (line.startsWith("test"){
doSomething();
}
Which is most efficient?
Which method is most effective for longer strings?
If I want to find Strings that start with “test” but then only ones which have “foo” after “test”, which method is better?
If Regex is the answer, what is the correct syntax for saying starts with “test” followed by “foo” or “bar” but not both?
Just use
startsWith. Regex is a bit overkill, unless you want to accept String with leading spaces.startsWithcan work with “test” or even “testfoo”. If you mean that"foo"can appear anywhere in the input after"test"(i.e."testokokokfoonothing"), then regex should be used here.Your code for regex version can be shortened to:
matches()check if the whole input matches the regex, so a bit of modification to the regex is necessary. The code above is slightly slower, since thePatternis recompiled.