我如何构造一个正则表达式来查找以字符串结尾但不以字符串开头的所有单词?
例如,在下面的句子中找到所有以'friend'结尾但不以'girl'开头的单词:
" 当他们要求与他们成为朋友时,男朋友和女朋友找到了一位朋友 "
粗体项应匹配."女朋友"这个词不应该.
Rob*_*sch 22
在我的头顶,你可以尝试:
\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
Run Code Online (Sandbox Code Playgroud)
更新
这是另一种非显而易见的方法,它应该适用于正则表达式的任何现代实现:
假设您希望提取出现在多个上下文中的模式,但只想在特定上下文中出现匹配,您可以使用更改,首先指定您不想要的内容,然后捕获您的操作.
因此,使用您的示例,提取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
Run Code Online (Sandbox Code Playgroud)
笔记:
这可以描述为:
在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);
Run Code Online (Sandbox Code Playgroud)
在运行时,将打印:
[ 'boyfriend', 'friend', 'befriend' ]
Run Code Online (Sandbox Code Playgroud)
这可能有效:
\w*(?<!girl)friend
你也可以试试
\w*(?<!girl)friend\w*
如果你想匹配像befriended
或的单词boyfriends
.
我不确定是否?<!
所有正则表达式版本都可用,但这个表达式在Expersso中工作(我相信它是.NET).