我将如何构造一个正则表达式来查找所有以字符串结尾但不以字符串开头的单词?
例如找出以下句子中所有以“ friend ”结尾但不以“女孩”开头的单词:
“一个 男朋友 和女朋友获得了一个 friend 当他们要求 成为 他们”
中的项目粗体 应该匹配。 “女朋友”这个词不应该。
最佳答案
在我的脑海中,你可以尝试:
\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
结尾的单词。除了 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' ]
关于正则表达式 - 查找所有不以特定前缀开头的匹配词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6308334/