正则表达式:匹配单引号中的字符串,但不匹配双引号内的字符串

6
我想写一个正则表达式来匹配用单引号括起来的字符串,但不应该匹配由双引号括起来的带有单引号的字符串。 示例1:
a = 'This is a single-quoted string';

整个值的a应该匹配,因为它被单引号包围。
编辑:精确匹配应为:'This is a single-quoted string' 示例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'
3个回答

8
假定不必处理转义引号(这是可能的,但会使正则表达式变得复杂),并且所有引号都正确平衡(没有像 It's... "Monty Python's Flying Circus"! 这样的情况),那么您可以查找单引号字符串,其后跟偶数个双引号:
/'[^'"]*'(?=(?:[^"]*"[^"]*")*[^"]*$)/g

在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)

1
谢谢,伙计。我把x放在了第一行,a放在了第二行。但是匹配返回的结果是错误的。http://regex101.com/r/tF5mB8 - s4m0k
@s4m0k:很好的发现,我编辑了正则表达式 - 现在更好了吗? - Tim Pietzcker
老兄,你是个天才!太完美了!非常感谢你!再加一分是因为你的解释很棒。 - s4m0k

1
尝试像这样:

试试这个:

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

实时演示


谢谢回复。但是这个正则表达式选择了单引号外的所有内容。它应该只匹配单引号中的确切字符串。 - s4m0k
嗯,但你说过这个:a的整个值应该匹配,因为它被单引号包围。 - NeverHopeless
没错,变量 a 的值是 '这是一个单引号括起来的字符串'。抱歉给你带来困惑,我修改了输出。 - s4m0k
我已经在实时演示中尝试过这个问题,y = '应该匹配';这里的某些字符串不应该匹配。但是它从y一直匹配到句点(.)。它只应该匹配“应该匹配”。 - s4m0k
感谢您的帮助。这很接近我想要的。但是我真正想要的输出是这个。http://regex101.com/r/sP6cM1 谢谢! - s4m0k

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接