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...!!!
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 boundarya[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 positionIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With