Re: Regular expression fails to replace but matches
On Aug 25, 7:17 pm, Daniele Futtorovic <da.futt.n...@laposte.invalid>
wrote:
On 25/08/2008 16:56, phillip.s.pow...@gmail.com allegedly wrote:
<pre>
<code>
// PATTERN: (<c:param.+value=")<%=[ \t]*([^%]+)[ \t]*%>(".*$)
Pattern p = Pattern.compile("(<c:param.+value=\")<%=[ \\t]*([=
^ \\t%]
+)[ \\t]*%>(\")");
Matcher matcher = p.matcher(stuff);
Pattern p2 = matcher.pattern();
System.out.println(p2.pattern());
if (matcher.find()) {
System.out.println("Found erroneous pattern \"<%= %>\" within =
\"" +
file.getName() + "\", converting now");
stuff = matcher.replaceAll("$1${$2}$3");
}
</code>
</pre>
This code works to find the JSTL tag pattern:
<pre>
<c:param name="[whatever]" value="<%= [whatever else] %>" />
</pre>
No it doesn't. Have you even bothered to test that code?
1. In your Pattern, second capturing group:
"([^ \\t%]+)"
If there's a whitespace in that character class, it won't match the
input above.
2. I'd suggest you be explicit about greediness. I'd suggest the
following Pattern instead of the one you used:
(<c:param.+?value=\")<%=[ \\t]*([^\\t%]+?)[ \\t]*%>(\")
-----------^----------------------------^ explicit reluctance
3. Replacement String: "$1${$2}$3". What group reference is "${$2}
supposed to be? That's not legit.
-.-
Bottom-line: before you happy-go-lucky around claiming that "Java can't
handle regular expressions", you should rather concern yourself with
whether your code actually does what you claim it does, and whether it
is even valid to begin with.
It was very valid, well, until I decided to use an incorrect pattern
syntax, loop via matcher.find() and use matcher.replaceFirst("$1\\
{$2}$3") - and BTW it IS legit, the braces are intentional
And now it works, though it shouldn't
--
DF.- Hide quoted text -
- Show quoted text -