java - Matching and replacing patterns using regex -
i want replace single quotes in string %27. single quotes must meet following conditions
- the single quote not @ start of line.
- the single quote not @ end of line.
- the single quote not preceded comma.
- the single quote not followed comma
for example 'a','b'c' become 'a','b%27c'
how do in java?
ignoring reason why choose regex task, can use following regex:
"(?<=[^,])'(?=[^,])"
note first solution assumes input doesn't contain new line character, makes start , end of line start , end of whole string. if assumption not apply, i.e. input contains new line character, please use second solution.
or longer version (this assumes no new line character in input string):
"(?<!^)(?<!,)'(?!$|,)"
i separated 2 look-behinds, since there a bug in java 1.5 , 1.4.2 affects look-behind alternation. if intend support java 1.6 , above, can combine 2 look-behinds (?<!^|,)
.
if want beginning of line instead of beginning of string, need enable multiline
flag (?m)
, makes ^
, $
matches start , end of line, instead of default start , end of string. example:
"(?m)(?<!^)(?<!,)'(?!$|,)"
Comments
Post a Comment