tags:

views:

149

answers:

2

I'm using replaceAll() on a string to replace any letter with "[two letters]". So xxxaxxx to xxx[ab]xxx. I don't want the ones that have already been replaced to be done again (turns to xxx[a[cb]]xxx)...

An easy way to do this would be to exclude any letters that are proceded by a "[" or followed by "]". What's the correct Regex to use?

replaceAll(foofoofoo, "[ab]");

+7  A: 
s.replaceAll("(?<!\\[)t(?!\\])", "[ab]");

These are respectively a negative lookbehind and a negative lookahead, two examples os zero-width assertions. More info can be found in Lookahead and Lookbehind Zero-Width Assertions.

One thing the above does it excludes [t]. I suspect that's what you want but if not, you'll need to modify it slightly.

cletus
Are you missing the final closing parenthesis there?
Tom Hawtin - tackline
yeah... need a ")" after the final closing bracket. Works perfectly, thanks!
cksubs
+1  A: 

You can use a negative lookbehind and lookahead, like this:

(?<!\[)t(?!=\])
Lucero