Java regexp overmatches
I want to replace a single <, but not <<, using a Java regexp (so I'm working with String.replaceAll()). Right no开发者_如何转开发w I have
([^<]|^)<([^<]|$)
which works in Python, but not Java. I have also tried negative look-around, with something like
(?<!<)<(?!<)
However, all my current attempts match << as well. Am I doing something wrong? Is there any Java-specifics here I don't know about?
If you want to replace a single "<" with an "X" say, do this:
String test = "hello << world < blah < blah << blah";
String _test = test.replaceAll("(^|[^<])<([^<]|$)", "$1X$2");
System.out.println(_test);
Gives you this:
hello << world X blah X blah << blah
Edit Updated to match at beginning and end of line
Your first regex contains a character class ([^<]|^)
. That's a positive match, so whatever gets caught in the character class will be replaced by replaceAll()
.
Your second regex only uses lookaround, which only verifies a condition, and does not match:
(?<!<)<(?!<)
That one works fine for me: it does not match <<
. Perhaps you can post a code snippet and some input/output that does not behave as you'd expect?
Perhaps you are using the wrong replacement?
\n is only used in backrefering to the capture group on the pattern side. You have to use $n to use it on the replacement side.
See http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html#replaceAll%28java.lang.String%29 for the documention on this.
精彩评论