java - Matching and replacing patterns using regex -


i want replace single quotes in string %27. single quotes must meet following conditions

  1. the single quote not @ start of line.
  2. the single quote not @ end of line.
  3. the single quote not preceded comma.
  4. 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

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -