Steve Steve - 1 year ago 41
Java Question

Understanding how Java's replaceFirst works with regular expressions

I have a String,

<parameter name="Browser" value="chrome" />
. I'd like to replace
. My relevant Java code:

l = l.replaceFirst("value=\"*\"", "value=\"" + browser + '"');

Is turning the original String into

<parameter name="Browser" value="Firefox"chrome" />
. I'm confused how
is not getting removed since the regex in
matches the opening and closing parentheses.

Answer Source

In the first regex, value=\"*\", the \"*\" is matching 0 or more " characters, not any number of characters as you intended. The correct syntax for this would be value=\".*\".

You can test out a regex on to get an idea of how your regex will work, with syntax highlighting.