gpt4 book ai didi

javascript - 查找之前没有特定字符的所有单词

转载 作者:行者123 更新时间:2023-11-30 21:20:18 25 4
gpt4 key购买 nike

如何找到之前没有特定字符的所有单词?

比如我要匹配所有apple,前面没有b字符,怎么办?

dolphin elephant apple star    <-- Matched
dog cat apple banana            <-- Matched
map banana apple dog           <-- Unmatched (Since there's a b before the apple)
map apple banana apple cat <-- The first apple matched, but the second one unmatched.
map apple banana apple banana apple <-- Only the first apple matched, others are unmatched.
map apple dog apple banana apple banana apple <-- The first apple and the second apple matched, others are unmatched.

这是我的尝试:

/(?<!.*b.*)apple/g

当然,上面的正则表达式是无效的,因为 lookbehind 中的量词(在本例中为星号)使其宽度不固定。那么我应该怎么做才能解决这个问题呢?

最佳答案

已经提到在 JS 正则表达式中没有可用的 lookbehind。对我来说,它读起来就像你想要匹配并最终替换特定字符之前的匹配词。

我会在第一次出现时拆分字符串,然后 capture the split sequence .然后仅在第一部分进行匹配/替换,然后重新加入这些部分。 [^]* 匹配任何字符。

// Test strings
var strs = ['dolphin elephant apple star','dog cat apple banana','map banana apple dog',
'map apple banana apple cat','map apple banana apple banana apple',
'map apple dog apple banana apple banana apple'];

// Split string at separator - Replace in first part - Rejoin
for (var str of strs) {
var parts = str.split(/(b[^]*)/);
parts[0] = parts[0].replace(/\b(apple)\b/g, '<b>$1</b>');
var new_str = parts.join('');

// Check result
console.log(new_str);
}

关于javascript - 查找之前没有特定字符的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45261268/

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