如何构建一个正则表达式来查找所有以某个字符串结尾但不以另一个字符串开头的单词?
例如,在以下句子中查找所有以“friend”结尾但不以“girl”开头的单词:
“当他们请求与他们交朋友时,男朋友和女朋友多了一个朋友。”
粗体字的单词应该匹配,单词“女朋友”不应该匹配。
如何构建一个正则表达式来查找所有以某个字符串结尾但不以另一个字符串开头的单词?
例如,在以下句子中查找所有以“friend”结尾但不以“girl”开头的单词:
“当他们请求与他们交朋友时,男朋友和女朋友多了一个朋友。”
粗体字的单词应该匹配,单词“女朋友”不应该匹配。
从我记忆中,你可以尝试以下方法:
\b # word boundary - matches start of word
(?!girl) # negative lookahead for literal 'girl'
\w* # zero or more letters, numbers, or underscores
friend # literal 'friend'
\b # word boundary - matches end of word
更新
以下是另一种不太明显的方法,在任何现代正则表达式实现中都应该适用:
假设您想要提取在多个上下文中出现的模式,但只有在特定上下文中出现时才匹配,您可以使用一个选择,首先指定您不想要的内容,然后捕获您需要的内容。
因此,以您的示例为例,要提取所有单词,这些单词要么是以friend
结尾,要么包含friend
但不是girlfriend
,您可以使用:
\b # word boundary
(?: # start of non-capture group
girlfriend # literal (note 1)
| # alternation
( # start of capture group #1 (note 2)
\w* # zero or more word chars [a-zA-Z_]
friend # literal
) # end of capture group #1
) # end of non-capture group
\b
注:
可以描述为:
Javascript代码:
const target = 'A boyfriend and girlfriend gained a friend when they asked to befriend them';
const pattern = /\b(?:girlfriend|(\w*friend))\b/g;
let result = [];
let arr;
while((arr=pattern.exec(target)) !== null){
if(arr[1]) {
result.push(arr[1]);
}
}
console.log(result);
运行时将会打印出以下内容:
[ 'boyfriend', 'friend', 'befriend' ]
可能会有效:
\w*(?<!女孩)朋友
如果你想匹配像 befriended
或者 男朋友
这样的单词,你也可以尝试:
\w*(?<!女孩)朋友\w*
。
我不确定在所有的正则表达式版本中是否都支持 ?<!
,但这个表达式在 Expersso 中可用(我相信它是.NET)。
试试这个:
/\b(?!girl)\w*friend\b/ig
\b(?![\w_]*Unwanted[\w_]*)[\w_]*Desired[\w_]*\b
?=&sysNew=false&sysStart=true&sysOffset=4&Question=1
前缀是sys
,我不知道哪些单词中有sys。
解决问题的关键在于单词边界\b
。
\b(?!sys)\w+\b
然后我将那部分添加到了用于查询字符串的更大正则表达式中。
(\b(?!sys)\w+\b)=(\w+)