Regex for quoted string with escaping quotes

2019-01-01 04:00发布

How do I get the substring " It's big \"problem " using a regular expression?

s = ' function(){  return " It\'s big \"problem  ";  }';     

15条回答
荒废的爱情
2楼-- · 2019-01-01 04:15

A more extensive version of https://stackoverflow.com/a/10786066/1794894

/"([^"\\]{50,}(\\.[^"\\]*)*)"|\'[^\'\\]{50,}(\\.[^\'\\]*)*\'|“[^”\\]{50,}(\\.[^“\\]*)*”/   

This version also contains

  1. Minimum quote length of 50
  2. Extra type of quotes (open and close )
查看更多
萌妹纸的霸气范
3楼-- · 2019-01-01 04:18

Messed around at regexpal and ended up with this regex: (Don't ask me how it works, I barely understand even tho I wrote it lol)

"(([^"\\]?(\\\\)?)|(\\")+)+"
查看更多
泪湿衣
4楼-- · 2019-01-01 04:19

If it is searched from the beginning, maybe this can work?

\"((\\\")|[^\\])*\"
查看更多
伤终究还是伤i
5楼-- · 2019-01-01 04:20

As provided by ePharaoh, the answer is

/"([^"\\]*(\\.[^"\\]*)*)"/

To have the above apply to either single quoted or double quoted strings, use

/"([^"\\]*(\\.[^"\\]*)*)"|\'([^\'\\]*(\\.[^\'\\]*)*)\'/
查看更多
栀子花@的思念
6楼-- · 2019-01-01 04:21
"(?:\\"|.)*?"

Alternating the \" and the . passes over escaped quotes while the lazy quantifier *? ensures that you don't go past the end of the quoted string. Works with .NET Framework RE classes

查看更多
旧时光的记忆
7楼-- · 2019-01-01 04:23

This one works perfect on PCRE and does not fall with StackOverflow.

"(.*?[^\\])??((\\\\)+)?+"

Explanation:

  1. Every quoted string starts with Char: " ;
  2. It may contain any number of any characters: .*? {Lazy match}; ending with non escape character [^\\];
  3. Statement (2) is Lazy(!) optional because string can be empty(""). So: (.*?[^\\])??
  4. Finally, every quoted string ends with Char("), but it can be preceded with even number of escape sign pairs (\\\\)+; and it is Greedy(!) optional: ((\\\\)+)?+ {Greedy matching}, bacause string can be empty or without ending pairs!
查看更多
登录 后发表回答