0

Finding trouble in getting the following regex work to put the string between quotes:

"\"mytext\"".replaceAll("^\"?|\"?$", "\"")

The above code gives - "mytext"" as the output, but what I require is "mytext".

For troubleshooting, I replaced the replaceWith character to * and the output is - *mytext**

Why is \"?$ considered as two separate matches?

James Jithin
  • 10,183
  • 5
  • 36
  • 51
  • FYI, you may use a regex to actually remove `"` chars at the start/end with `.replaceAll("^\"+|\"+$", "")`, and then add quotes. If you want to practice regex you may use a single `replaceAll("(?s)^\"*(.*?)\"*$", "\"$1\"")` call. – Wiktor Stribiżew Mar 26 '19 at 08:01
  • You are welcome. Mind that empty string matching patterns in regex `replace` methods are rather tricky, you should really know what you are doing when using them. – Wiktor Stribiżew Mar 26 '19 at 08:06
  • Sure. Thanks for the tip @WiktorStribiżew! – James Jithin Mar 26 '19 at 08:09

0 Answers0