I'm trying to figure out a javascript regex that'll match an exact phrase that ends with a question mark, but isn't wrapped in quotes. So far I have this, which matches the phrase "some phrase", but I can't figure out how to match "some phrase?". Any help would be greatly appreciated.
我试图找出一个javascript正则表达式,它匹配一个以问号结尾的精确短语,但不包含在引号中。到目前为止,我有这个,它匹配短语“some phrase”,但我无法弄清楚如何匹配“某些短语?”。任何帮助将不胜感激。
(?<!"|')\some phrase\b(?!"|')
2 个解决方案
#1
2
Lookbehinds don't exist in JavaScript. Use the following pattern:(?:[^"']|^)(some phrase\?)(?!["'])
. [^"']|^
means: any non-quote character or the beginning of a string.
JavaScript中不存在Lookbehinds。使用以下模式:(?:[^“'] | ^)(某些短语\?)(?![”'])。 [^“'] | ^表示:任何非引号字符或字符串的开头。
Example:
例:
var text = "....";
var pattern = /(?:[^"']|^)(some phrase\?)(?!["'])/;
var string = text.match(pattern);
var desiredString = string[1]; //Get the grouped text
var patternWithNQuoteGrouped = /([^"']|^)(some phrase\?)(?!["'])/;//Notice: No ?:
var replaceString = text.replace(patternWithNQuoteGrouped, '$1$2');
//$1 = non-quote character $2 = matched phrase
The parentheses around the phrase mark a referable group. (?:
means: Create a group, but dereference it. To refer back to it, see the example code. Because lookbehinds don't exist in JavaScript, it's not possible to create a pattern which checks whether a prefix does not exist.
短语周围的括号标记可参考组。 (?:表示:创建一个组,但取消引用它。要返回它,请参阅示例代码。由于JavaScript中不存在lookbehinds,因此无法创建检查前缀是否不存在的模式。
#2
1
Try this:
尝试这个:
var expr = /(^|(?!["']).)(some phrase\?)($|(?!["']).)/;
if (expr.test(searchText)) {
var matchingPhrase = RegExp.$2;
}
http://jsfiddle.net/gilly3/zCUsg/
http://jsfiddle.net/gilly3/zCUsg/
#1
2
Lookbehinds don't exist in JavaScript. Use the following pattern:(?:[^"']|^)(some phrase\?)(?!["'])
. [^"']|^
means: any non-quote character or the beginning of a string.
JavaScript中不存在Lookbehinds。使用以下模式:(?:[^“'] | ^)(某些短语\?)(?![”'])。 [^“'] | ^表示:任何非引号字符或字符串的开头。
Example:
例:
var text = "....";
var pattern = /(?:[^"']|^)(some phrase\?)(?!["'])/;
var string = text.match(pattern);
var desiredString = string[1]; //Get the grouped text
var patternWithNQuoteGrouped = /([^"']|^)(some phrase\?)(?!["'])/;//Notice: No ?:
var replaceString = text.replace(patternWithNQuoteGrouped, '$1$2');
//$1 = non-quote character $2 = matched phrase
The parentheses around the phrase mark a referable group. (?:
means: Create a group, but dereference it. To refer back to it, see the example code. Because lookbehinds don't exist in JavaScript, it's not possible to create a pattern which checks whether a prefix does not exist.
短语周围的括号标记可参考组。 (?:表示:创建一个组,但取消引用它。要返回它,请参阅示例代码。由于JavaScript中不存在lookbehinds,因此无法创建检查前缀是否不存在的模式。
#2
1
Try this:
尝试这个:
var expr = /(^|(?!["']).)(some phrase\?)($|(?!["']).)/;
if (expr.test(searchText)) {
var matchingPhrase = RegExp.$2;
}
http://jsfiddle.net/gilly3/zCUsg/
http://jsfiddle.net/gilly3/zCUsg/