正则表达式匹配以问号结尾的短语

发布于 2024-12-12 00:08:07 字数 179 浏览 0 评论 0原文

我正在尝试找出一个 javascript 正则表达式,它将匹配以问号结尾但不包含在引号中的确切短语。到目前为止,我有这个,它与短语“somephrase”匹配,但我不知道如何匹配“somephrase?”。任何帮助将不胜感激。

(?<!"|')\some phrase\b(?!"|')

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.

(?<!"|')\some phrase\b(?!"|')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最冷一天 2024-12-19 00:08:07

JavaScript 中不存在 Lookbehind。使用以下模式:
(?:[^"']|^)(某些短语\?)(?!["'])[^"']|^ 表示:任何非引号字符字符串的开头。

示例:

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

短语周围的括号标记可引用的组。(?: 表示:创建一个组,但取消引用它。要引用它,请参阅示例代码。因为 JavaScript 中不存在后向查找,所以不可能创建一个检查前缀是否存在的模式不存在。

Lookbehinds don't exist in JavaScript. Use the following pattern:
(?:[^"']|^)(some phrase\?)(?!["']). [^"']|^ means: any non-quote character or the beginning of a string.

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.

唔猫 2024-12-19 00:08:07

试试这个:

var expr = /(^|(?!["']).)(some phrase\?)($|(?!["']).)/;
if (expr.test(searchText)) {
    var matchingPhrase = RegExp.$2;
}

http://jsfiddle.net/gilly3/zCUsg/

Try this:

var expr = /(^|(?!["']).)(some phrase\?)($|(?!["']).)/;
if (expr.test(searchText)) {
    var matchingPhrase = RegExp.$2;
}

http://jsfiddle.net/gilly3/zCUsg/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文