gpt4 book ai didi

Javascript正则表达式捕获组中的单词和分隔符

转载 作者:行者123 更新时间:2023-11-27 23:53:26 33 4
gpt4 key购买 nike

我在 Javascript 中使用这个正则表达式捕获两个组。第一个是捕获单词 Hello,第二个是捕获以下分隔符,例如 !,等等,给定字符串 Hello!我听到了

这是我正在使用的表达方式:

/(\b[^\s]+\b)?(\W+)/g

The example is accessible here 。我遇到的问题是,在没有后续分隔符的情况下,我想捕获源字符串中的最后一个单词(以捕获组 1)。在我链接到的示例中,您可以看到最后一个单词 part 未被捕获。

我尝试了多种变体,但最终匹配的次数是无限的。

最佳答案

更新:this怎么样? :

(\b[^\s]+\b)?(\W*) -->匹配空字符串(如@anubhava所述)

(\b[^\s]+\b)?(?:(\W+)|$) --> 不匹配空字符串

var re = /(\b[^\s]+\b)?(?:(\W+)|$)/g; 
var str = '.Balch Creek is a 3.5-mile (5.6 km) tributary of the Willamette River in the U.S. state of Oregon. Beginning at the crest of the Tualatin Mountains, the creek flows generally east down a canyon and through Forest Park, a large municipal park in Portland. It then enters a pipe and remains underground until reaching the river. Danford Balch, after vegetation. Sixty-two species of mammals and more than 112 species of birds use Forest Park. A small population of coastal cutthroat trout resides in the stream, which in 2005 was the only major water body in Portland that met state standards for bacteria, temperature, and dissolved oxygen. Although nature reserves cover much of the upper and middle parts of the watershed, industrial sites dominate the lower part';
var m;

while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
document.getElementById("r").innerHTML += "Group 1: " + m[1] + "<br/>Group 2: " + m[2] + "<br/><br/>";

}
<div id="r"/>

关于Javascript正则表达式捕获组中的单词和分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32488449/

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