Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace word using java regex but not quotes

I want to replace a word in a sentence using java regex replace.

test string is a_b a__b a_bced adbe a_bc_d 'abcd' ''abcd''

if i want to replace all the words which starts with a & ends with d. i'm using String.replaceAll("(?i)\\ba[a-zA-Z0-9_.]*d\\b","temp").

its replacing as a_b a__b temp adbe a_bc_d 'temp' ''temp''

What should be my regex if i don't want to consider the string in quotes.?

I used String.replaceAll("[^'](?i)\\ba[a-zA-Z0-9_.]*d\\b[^']","temp") Its replacing as a_b a__btempadbe temp'abcd' ''abcd''. Its removing one spaces of that word. Is there any way to replace only that string not inside the quotes?

PS: there is a workaround for this String.replaceAll("[^'](?i)\\ba[a-zA-Z0-9_.]*d\\b[^']"," temp "). But it fails in some cases.

What should be my regex if i want to replace a word in a sentence & i should not consider string in side quotes.? Thanks in Advance...!!!

like image 394
anji_rajesh Avatar asked Mar 06 '26 10:03

anji_rajesh


1 Answers

You can use lookaround assertions:

string = string.replaceAll("(?i)(?<!')\\ba[a-zA-Z0-9_.]*d\\b(?!')", "temp");

RegEx Demo

Read more about lookarounds

RegEx Details:

  • (?i): Turn mode to ignore case
  • (?<!'): Negative lookbehind to make sure there is no ' right before the current position
  • \b: Word boundary
  • a[a-zA-Z0-9_.]*: Match letter a followed by 0 or more of any character inside the character class [...]
  • d: Match letter d
  • \b: Word boundary
  • (?!'): Negative lookahead to make sure there is no ' right after the current position
like image 164
anubhava Avatar answered Mar 08 '26 22:03

anubhava