Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

java - Regex, proper escaping for " (groovy)

My second day coding java/groovy so bare with me :)

In short, I'm trying to replace " with \"

string = string.replaceAll()

I've tried with any number of backslashes, and as I expect with 0-1 backslashes it catches any " in the string, but so it does also with two or three. With four I can match \\", again as I'd expect. Why is this and what's the solution?

My actual aim is to parse merge request changes, where the diff field has the raw version with " and which causes problems with JsonSlurper. I managed to deal with linebreaks using

string = string.replaceAll(/\
/, /\\
/)

but with quotation mark the same approach just doesn't seem to work.

Thanks for help.

Edit: For extra clarity teststring = ' Zero " One " Two \" ' I haven't been able to change case One without also changing Zero. Case two is handled by 4 backslashes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It works also for ":

teststring = $/ Zero " One " Two \" /$
println teststring.replaceAll(/\"/, /\\"/)

with the output:

Zero " One \" Two \"

The difference makes the slashy-string. You must be very careful with the input string: 'test"' is the same as 'test"' if you use single quoted strings. Then in this case, you must escape both the and the ".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...