Replacing comma with any special character in string using java Regex -
i want replace commas 1 special character (e.g "#") present inside double quotes in java.
below string :
string line="\"lee, rounded, neck, printed\",410.00,300.00,\"red , blue\",lee";
output :
"lee# rounded# neck# printed",410.00,300.00,"red # blue",lee
i have tried :
public class str { public static void main(string[] args) { string line="\"lee, rounded, neck, printed\",410.00,300.00,\"red , blue\",lee"; string linedelimiter=","; string templine=line; if(templine!=null && templine.contains("\"")) { pattern p=pattern.compile("(\".*?"+pattern.quote(linedelimiter)+".*?\")"); matcher m=p.matcher(templine); if(m.find()) { (int = 1; <= m.groupcount(); i++) { string temp=m.group(i); string temp1=temp; temp=temp.replaceall("(,)", " ## "); line=line.replaceall(pattern.quote(temp1),pattern.quote(temp)); } } } } }
using above code able find first occurances of string present inside quotes not second one("red , blue").
following code should work:
string line="\"lee, rounded, neck, printed\",410.00,300.00,\"red , blue\",lee"; string repl = line.replaceall(",(?!(([^\"]*\"){2})*[^\"]*$)", "#"); system.out.println("replaced => " + repl);
output:
"lee# rounded# neck# printed",410.00,300.00,"red # blue",lee
explanation: regex means match comma if not followed number of double quotes. in other words match comma if inside double quotes.
ps: assuming there no unbalanced double quotes , there no case of escaped double quotes.
Comments
Post a Comment