如何匹配所有单词,除非它们包含点,例如
I want to match everything except.this and similar words with dots in them
我尝试了 \b(?!\w+\.\w+)\w+\b
但这不起作用。
无论我如何使用 \w+
、\\.
等,正则表达式引擎仍然匹配“ignore.me”部分点后面。有一个简单的语法吗?仅仅转义点似乎不起作用。
最佳答案
我建议如下pattern :
(?:^|\s)(?:(?!\.)[\w'])+(?=\s|$|[.?!](?:\s|$))
JS/正则表达式测试:
const regex = /(?:^|\s)(?:(?!\.)[\w'])+(?=\s|$|[.?!](?:\s|$))/g;
const str = `aaa blabla fasdfdsa ignoremenot.
bbb igno.reme ad
It's fine?`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match.trim()}`);
});
}
有一个问题:您必须 trim 匹配项以删除可能出现的不必要的空格,因为我们无法在 JavaScript 的正则表达式中使用lookbehind,如下所示:(?<=^|\s)(?:(?!\.)[\w'])+(?=\s|$|[.?!](?:\s|$))
关于javascript - 匹配每个单词,除非它包含文字点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47613464/