首页 文章

RegEx:匹配用单引号括起来的字符串,但不匹配双引号内的字符串

提问于
浏览
4

我想写一个正则表达式来匹配用单引号括起来的字符串,但是不应该匹配带有双引号的单引号的字符串 .

Example 1:

a = 'This is a single-quoted string';

a 的整个值应匹配,因为它用单引号括起来 .

编辑:完全匹配应该是: 'This is a single-quoted string'

Example 2:

x = "This is a 'String' with single quote";

x 不应返回任何匹配项,因为单引号位于双引号内 .

我试过 /'.*'/g 但它也匹配双引号字符串中的单引号字符串 .

Thanks for the help!

编辑:

使它更清楚

鉴于以下字符串:

The "quick 'brown' fox" jumps
over 'the lazy dog' near
"the 'riverbank'".

匹配应该只是:

'the lazy dog'

3 回答

  • 6

    假设不必处理转义引号(这可能会使正则表达式复杂化),并且所有引号都是正确 balancer 的(没有像 It's... "Monty Python's Flying Circus"! 那样),那么你可以查找单引号字符串,后跟一个偶数双引号:

    /'[^'"]*'(?=(?:[^"]*"[^"]*")*[^"]*$)/g
    

    看到它live on regex101.com .

    Explanation:

    '        # Match a '
    [^'"]*   # Match any number of characters except ' or "
    '        # Match a '
    (?=      # Assert that the following regex could match here:
     (?:     # Start of non-capturing group:
      [^"]*" # Any number of non-double quotes, then a quote.
      [^"]*" # The same thing again, ensuring an even number of quotes.
     )*      # Match this group any number of times, including zero.
     [^"]*   # Then match any number of characters except "
     $       # until the end of the string.
    )        # (End of lookahead assertion)
    
  • 0

    尝试这样的事情:

    ^[^"]*?('[^"]+?')[^"]*$
    

    现场演示

  • 1

    如果你没有严格限制正则表达式,你可以使用函数“indexOf”来查明它是否是双引号匹配的子字符串:

    var a = "'This is a single-quoted string'";
    var x = "\"This is a 'String' with single quote\"";
    
    singlequoteonly(x);
    
    function singlequoteonly(line){
        var single, double = "";
        if ( line.match(/\'(.+)\'/) != null ){
            single = line.match(/\'(.+)\'/)[1];
        }
        if( line.match(/\"(.+)\"/) != null ){
            double = line.match(/\"(.+)\"/)[1];
        }
    
        if( double.indexOf(single) == -1 ){
            alert(single + " is safe");
        }else{
            alert("Warning: Match [ " + single + " ] is in Line: [ " + double + " ]");
        }
    }
    

    请参阅下面的JSFiddle:

    JSFiddle

相关问题