Negative lookarounds with regex
Morning folks,
I'm attempting to construct a pattern that will allow me to modify an example string from this;
" #99; c # "
to this;
" #99; c # "
The pattern that I've come up with is intended to match the hash character (#) only when it is not preceeded by an ampersand (&)and is not followed by two digits and a semicolon. Unfortunately though, no match is found.
String source =" #99; c # ";
System.out.println(source.replaceAll("(?<!&)#(?!\\d\\d;)","#"));
Any suggestions as to alternatives I can try, or other places I could look, would be most appreciated.>
Sabre,That catches the hash on its own at the end of the string, but not the hash at the start, producing output as follows;" #99; c # "Any other ideas folks ? (J2SDK 1.4.2 BTW)
> I'm attempting to construct a pattern that will allow me to modify an example string from this;>" #99; c # "
> to this;> " #99; c # "
> The pattern that I've come up with is intended to match the hash character (#) only when it is not
> preceeded by an ampersand (&) and is not followed by two digits and a semicolon.
Make your mind up. The first replacement in your example (" #99; " -> " #99; ") is replacing a hash character which is followed by two digits and a semicolon.
That's right. You really only have to make a rule that works when the previous character is not &. Try this:
String source = " #99; c # ";
System.out.println(source.replaceAll("(?<!&)#", "#"));
>