I need to match the following string with regular expressions in Java:
Hello: ${firstName} ${lastName}
And get this:
${firstName}
${lastName}
I tried this:
@Test
public void testRegexMatch() {
String regex = Pattern.quote("${") + ".+" + Pattern.quote("}");
String str = "Hello: ${firstName} ${lastName}";
Matcher m = Pattern.compile(regex).matcher(str);
while (m.find()) {
System.out.println(str.substring(m.start(), m.end()));
}
}
But I got the following output:
${firstName} ${lastName}
try replacing
.+with[^\}]+. which will match as many non-}characters as it can.It is also important to note that this method is superior to using the non-greedy quantifier
.+?because this will match without any backtracking, while the non-greedy version will backtrack once per character within the brackets. In this case, you will probably not notice a performance hit, but it is important to be in the habit of writing the most efficient regular expressions possible