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;)","&#35;"));

Any suggestions as to alternatives I can try, or other places I could look, would be most appreciated.>

[797 byte] By [schurchilla] at [2007-10-1 2:57:47]
# 1
String source = " #99; c # ";System.out.println(source.replaceAll("#(?<!&)(?!\\d\\d;)", "&#35;"));>
sabre150a at 2007-7-8 15:36:08 > top of Java-index,Java Essentials,Java Programming...
# 2
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)
schurchilla at 2007-7-8 15:36:08 > top of Java-index,Java Essentials,Java Programming...
# 3

> 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.

YATArchivista at 2007-7-8 15:36:08 > top of Java-index,Java Essentials,Java Programming...
# 4

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("(?<!&)#", "&#35;"));

>

stevejlukea at 2007-7-8 15:36:08 > top of Java-index,Java Essentials,Java Programming...
# 5
Thanks Steve :^)I'd blinded myself to the simple answer by adding in an extra condition that never needed to be there. Oh well, live and learn ...
schurchilla at 2007-7-8 15:36:08 > top of Java-index,Java Essentials,Java Programming...