java - Replace a substring in a string except when the string is inside quotes -
regex dialect: java
problem: given string, replace occurrences of substring inside it, except when these occurrences inside quotes.
example1:
string: "test substr 'test substr' substr" substring: "substr" replacement: "yyyy" output: "test yyyy 'test substr' yyyy"
example2:
string: "test sstr 'test sstr' sstr" substring: "substr" replacement: "yyyy" output: "test sstr 'test sstr' sstr"
example3:
string: "test 'test substr'" substring: "substr" replacement: "yyyy" output: "test 'test substr'"
this best try far:
regex: ((?:[^']*'[^']+')*?[^']*?)substring replace: $1replacement
the problem needs substring outside quotes after last string within quotes otherwise doesn't work, example3 fail (output: "test 'test yyyy'").
many help.
here's way:
public class main { public static void main(string [] args) { string[] tests = { "test substr 'test substr' substr", "test sstr 'test sstr' sstr", "test 'test substr'" }; string regex = "substr(?=([^']*'[^']*')*[^']*$)"; for(string t : tests) { system.out.println(t.replaceall(regex, "yyyy")); } } }
prints:
test yyyy 'test substr' yyyy test sstr 'test sstr' sstr test 'test substr'
note not work if '
can escaped \
example.
a quick explanation:
the following: ([^']*'[^']*')*
match 0 or number of single quotes non quotes in between, , [^']*$
matches non-quotes , end-of-string.
so, complete regex substr(?=([^']*'[^']*')*[^']*$)
matches "substr"
has 0 or number of single quotes ahead of it, when looking way end-of-string!
looking way end-of-string key here. if wouldn't that, following "substr"
replaced:
aaa 'substr' bbb 'ccc ddd' eee ^ ^ ^ | | | ii iii
because "sees" number of single quotes ahead of (i , ii). must force @ entire string right of (all way $
)!
Comments
Post a Comment