匹配用单引号括起来的字符串,但不匹配双引号括起来的字符串
RegEx : Match a string enclosed in single quotes but don't match those inside double quotes
我想写一个正则表达式来匹配用单引号括起来的字符串,但不应该匹配用单引号括起来的字符串
示例1:
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'
假设不需要处理转义引号(这是可能的,但会使正则表达式变得复杂),并且所有引号都是正确平衡的(不像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)
试试这样:
^[^"]*?('[^"]+?')[^"]*$
现场演示
如果您没有严格限制regex,您可以使用函数"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
相关文章:
- 如何使用python将大量unicode隐藏为char,使其看起来像字符串
- 如何将字符串与变量连接起来/传递到链接
- 当附加到DOM时,可以将变量与字符串连接起来吗?它能处理逃跑吗
- 调用一个位于字符串内部的JavaScript函数,并将params与一个变量连接起来
- JavaScript:将一个整数与一长串字符串关联起来
- 将看起来像数组的字符串转换为实际数组
- 是否可以在 JavaScript 中将 OBJ 与字符串连接起来
- Angularjs 将字符串与多复选框连接起来
- 在 JavaScript 中将变量字符串括起来
- JavaScript:如何用包含唯一id的span标记将字符串中的每个单词包装起来
- 我有一个字符串,它包含一个小数点;10.00〃;我想用jQuery把它隐藏起来
- 将每个数字转换为字符串并连接起来
- javascript:如何将字符串数组转换为纯字符串,该字符串将以逗号分隔的项连接起来
- 字符串比较-两个字符看起来相同,但具有不同的ASCII值
- 只有字符串中的单词用引号括起来- JavaScript
- 用空格分隔的值对字符串进行标记,除非值用单引号括起来
- 如果子字符串不在正则表达式中,则用双引号括起来
- 为什么这三个正则表达式会拆分字符串差异,尽管它们看起来是等效的
- 为什么我必须把字符串推入数组,然后再把它连接起来呢?
- 如何将正则表达式与字符串变量连接起来