gpt4 book ai didi

javascript文本匹配计数和正则表达式空格不起作用

转载 作者:行者123 更新时间:2023-11-28 01:07:52 25 4
gpt4 key购买 nike

我有一个问题。我正在生成一个用于文本匹配续和排序匹配计数的小脚本。 click to see jsfiddle live example

我的示例脚本:

var testtext1 = "apple banana and kiwi pineapple juice";
var testtext2 = "need apple banana pineapple milkshake";
var testtext3 = "apple pineapple lower prices";
var testtext4 = "only apple banana kiwi pineapple lovers";
var testtext5 = "kiwi pineapple apple banana sales";

alert(testtext1.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //3 matches
alert(testtext2.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //2 m
alert(testtext3.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //2 m
alert(testtext4.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //2 m
alert(testtext5.match(/apple banana kiwi|apple banana|apple|banana|kiwi/gi).length); //3 matches

text1= 只有 3 个匹配,为什么?观察正则表达式

苹果香蕉猕猴桃或苹果香蕉或苹果或香蕉或猕猴桃

苹果香蕉猕猴桃不匹配0

苹果香蕉是匹配1

苹果是匹配2

香蕉是匹配3

猕猴桃是匹配4

好吧,为什么返回 3 个匹配项而不是 4 个匹配项?和其他例子?

see matchs this pic ?

最佳答案

看看下面的演示

Live DEMO

用单词边界包围它,否则 pineapple 将与 apple 匹配

\b(apple banana kiwi|apple banana|apple|banana|kiwi)\b

比赛

apple banana and kiwi pineapple juice        2
need apple banana pineapple milkshake 1
apple pineapple lower prices 1
only apple banana kiwi pineapple lovers 1
kiwi pineapple apple banana sales 2
<小时/>

编辑

如果改变顺序,结果就会不同

\b(apple|banana|apple banana kiwi|apple banana|kiwi)\b

Live DEMO

apple banana and kiwi pineapple juice        3

关于javascript文本匹配计数和正则表达式空格不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24854401/

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