gpt4 book ai didi

javascript - 正则表达式通配符问题

转载 作者:行者123 更新时间:2023-12-02 20:08:32 25 4
gpt4 key购买 nike

代码:

strx = "exam/unwanted_tex/ple";
strx = strx.replace(/\/.+\//, '');
alert(strx); // Alerts "example"

2 个简单问题:

  1. 此代码会替换“/”和“/”内的所有内容?
  2. 使用“.*”而不是“.+”有什么区别

最佳答案

  1. '*''+' 称为量词。 '*' 匹配其前面零次或多次的字符或组。从某种意义上说,这使得匹配成为可选的。 '+' 匹配前面一次或多次的字符或组。在您的特定示例中,没有实际差异。然而,当在其他应用程序中使用时,这种区别非常重要。这是一个例子:

'*' 量词(匹配零次或多次)

// Match 'y' in Joey zero or more times
strx = "My name is Joe";
strx = strx.replace(/Joey*/, 'Jack');
alert(strx) // Alerts "My Name is Jack"

'+'量词(匹配一次或多次)

// Match 'y' in Joey one or more times
strx = "My name is Joe";
strx = strx.replace(/Joey+/, 'Jack');
alert(strx) // Alerts "My Name is Joe"

关于javascript - 正则表达式通配符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7199125/

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