Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex to match "t" except when it's "[t" or "t]"

Tags:

java

regex

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]");

like image 901
ck_ Avatar asked Mar 01 '23 18:03

ck_


1 Answers

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.

like image 124
cletus Avatar answered Mar 12 '23 14:03

cletus