gpt4 book ai didi

javascript - 正则表达式 : get word without word before it

转载 作者:行者123 更新时间:2023-12-03 06:46:51 26 4
gpt4 key购买 nike

有一个文件包含大量“lore ipsum Bar lore ipsum”“lorem ipsuem Foo Bar lorem ipsuem”

如何通过正则表达式获取所有出现的 Bar 而没有 Foo(忽略所有“Foo Bar”,选择“Bar”)?

类似于:

^(?!.*Foo)。酒吧*$

??

最佳答案

^(?!.*Foo)。 Bar*$ 模式匹配器是一个内部没有 Foo 的字符串,并且以除换行符之外的任何字符开头,后跟一个空格,然后以 Ba + 零个或多个 r。我怀疑你在现实生活中是否需要这个正则表达式。

您可以使用 replace 方法中的回调方法来完成此操作,使用已知的正则表达式技巧首先匹配您不需要的内容,然后匹配并捕获您需要的内容。

参见this regex :

\bFoo Bar\b|(\bBar\b)
^--match--^ ^-capture-^

我用单词边界包裹了单词,如果您搜索的字符串的开头/结尾没有单词字符,您可能会丢弃它们。

var re = /\bFoo Bar\b|(\bBar\b)/g;    // Declare the regex
var str = 'lore ipsum Bar lore ipsum\nlorem ipsuem Foo Bar lorem ipsuem';
var subst = '<b>Foo Bar</b>'; // A sample substitution
var result = str.replace(re, function($0, $1) { // Use the anonymous method
return $1 ? subst : $0; // If Group 1 matches, use a subst, else, reinsert the match back
});
document.body.innerHTML = result;

关于javascript - 正则表达式 : get word without word before it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37700007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com