【问题标题】:RegEx : Match a string enclosed in single quotes but don't match those inside double quotesRegEx:匹配单引号内的字符串,但不匹配双引号内的字符串
【发布时间】:2014-05-02 19:46:01
【问题描述】:

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

示例 1:

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

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

编辑:完全匹配应该是: '这是一个单引号字符串'

示例 2:

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

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

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

感谢您的帮助!

编辑:

为了更清楚

给定以下字符串:

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

匹配应该只有:

'the lazy dog'

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

    试试这样的:

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

    Live Demo

    【讨论】:

    • 感谢您的回复。但是这个正则表达式选择了单引号之外的所有内容。它应该只匹配单引号中的确切字符串。
    • 嗯,但你是这么说的:the whole value of a should match because it is enclosed with single quotes.
    • 没错,a 的值是“这是一个单引号字符串”。抱歉,我编辑了输出。
    • 我在现场演示中试过这个,y = 'Should match';此处的某些字符串不应该匹配。 但它匹配从 y 到点 (.)。它应该只匹配“应该匹配”
    • 感谢您的帮助。这接近我想要的。但我真正想要的输出是这个。 regex101.com/r/sP6cM1 谢谢!
    【解决方案2】:

    如果您不受正则表达式的严格限制,您可以使用函数“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

    【讨论】:

      【解决方案3】:

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

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

      live on regex101.com

      说明:

      '        # 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)
      

      【讨论】:

      • 谢谢老兄,我把 x 放在最上面,把 a 放在第二行。返回的匹配是错误的。 regex101.com/r/tF5mB8
      • @s4m0k:很好,我编辑了正则表达式——现在更好了吗?
      • 天哪,你真是个天才!完美的!太感谢了!和 +1 的解释
      猜你喜欢
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2014-09-26
      • 2011-01-30
      相关资源
      最近更新 更多