【问题标题】:Javascript regex capturing words and separators in groupsJavascript 正则表达式在组中捕获单词和分隔符
【发布时间】:2015-09-11 20:10:37
【问题描述】:

我在 Javascript 中有这个正则表达式捕获两个组。第一个是捕获单词Hello,第二个是捕获以下分隔符,例如!,依此类推,给定一个字符串Hello! I hear you

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

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

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

我尝试了许多变体,但最终得到了无数次匹配。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    更新: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/>";
        
    }
    &lt;div id="r"/&gt;

    【讨论】:

    • 正是我实际尝试过的那个,但由于某种原因,我得到了无数个匹配项。
    • 我很困惑 - 我想我不确定你想捕捉什么。给定示例输入,您能否发布您期望捕获的内容?
    • 为什么是无限的?你有什么问题?请看this fiddle
    • @stribizhev re.lastIndex++; 成功了。我必须承认(好像这并不明显)我并不完全理解 Javascript 中的 exec 方法。
    • @NumericOverflow:我建议您将 JS 代码添加到您的答案中。
    【解决方案2】:

    你可以使用这个正则表达式:

    /(\S+)(\W*)/g
    

    最后一组中的(\W*) 将使其匹配0个或多个非单词字符。

    也无需在\S+ 周围使用单词边界。

    RegEx Demo

    【讨论】:

    • 谢谢,但是这个解决方案有一些问题:首先)第一个点没有在 $2 中捕获。第二)我实际上想在一个 $1 中捕获整个 3.5-mile
    • 越来越近了:)。尽管如此,“单词”部分,即捕获组 $1,应该以 \b 开头并以 \b 结尾。
    • \S+ 周围使用\b 将使它从.Balch 跳过DOT
    • 还要注意(\b\S+\b)?(\W*)会匹配空字符串""也匹配as in this example
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多