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:26

here is one that work with both " and ' and you easily add others at the start.

("|')(?:\\\1|[^\1])*?\1

it uses the backreference (\1) match exactley what is in the first group (" or ').

http://www.regular-expressions.info/backref.html

查看更多
孤独总比滥情好
3楼-- · 2019-01-01 04:27
/"(?:[^"\\]|\\.)*"/

Works in The Regex Coach and PCRE Workbench.

Example of test in JavaScript:

    var s = ' function(){ return " Is big \\"problem\\", \\no? "; }';
    var m = s.match(/"(?:[^"\\]|\\.)*"/);
    if (m != null)
        alert(m);

查看更多
心情的温度
4楼-- · 2019-01-01 04:28
/"(?:[^"\\]++|\\.)*+"/

Taken straight from man perlre on a Linux system with Perl 5.22.0 installed. As an optimization, this regex uses the 'posessive' form of both + and * to prevent backtracking, for it is known beforehand that a string without a closing quote wouldn't match in any case.

查看更多
登录 后发表回答