簡體   English   中英

Javascript正則表達式捕獲組中的單詞和分隔符

[英]Javascript regex capturing words and separators in groups

我在Javascript中有這個正則表達式,可以捕獲兩個組。 第一個是捕獲單詞Hello ,第二個是捕獲以下分隔符,如! ,等等給定一個字符串Hello! I hear you Hello! I hear you

這是我正在使用的表達式:

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

該示例可在此處訪問 我遇到的問題是,對於沒有后續分隔符的情況,我想捕獲源字符串中的最后一個單詞(以捕獲組1)。 在我鏈接到的示例中,您可以看到未捕獲最后一個單詞part

我嘗試了多種變體,但最終卻遇到了無數次比賽。

更新:怎么樣這個

(\\ 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 US 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"/> 

您可以使用此正則表達式:

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

最后一組中的(\\W*)將使其匹配0個或多個非單詞字符。

同樣也不需要在\\S+周圍使用單詞邊界。

正則演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM