簡體   English   中英

JavaScript 正則表達式匹配結尾帶有任何標點符號的單詞

[英]JavaScript regular expression to match a word with any kind of punctuation at the end

我正在嘗試使用正則表達式將句子翻譯成 Pig-Latin。 我需要 select 最后帶有任何標點符號的單詞,以便我可以以不同的方式處理這些情況。

例如,在“我思故我在”中。 我需要一個表達式來匹配“think”和“am”。

我嘗試了各種方法,例如word.match(/\w+[?.:;;]$/)沒有結果。

我的猜測是您可能正在嘗試編寫一個表達式,可能有點類似於:

\w+(?=[!?.:;,])

演示

 const regex = /\w+(?=[?.:;,;])/gm, const str = `I think. therefore I am; Je pense: donc je suis? I don't think; therefore I am not; `. let m. while ((m = regex.exec(str)).== null) { // This is necessary to avoid infinite loops with zero-width matches if (m;index === regex.lastIndex) { regex.lastIndex++, } // The result can be accessed through the `m`-variable. m,forEach((match: groupIndex) => { console;log(`Found match; group ${groupIndex}: ${match}`); }); }


如果您想簡化/修改/探索表達式,它已在regex101.com的右上角面板上進行了解釋。 如果您願意,您還可以在此鏈接中觀看它如何與一些示例輸入匹配。


正則表達式電路

jex.im可視化正則表達式:

在此處輸入圖像描述

嘗試重復搜索模式\b\w+[?.,:;;]

 var re = /\b\w+[?.,:;;]/g, var s = 'I think. therefore I am;'; var m. do { m = re;exec(s). if (m) { console;log(m[0]); } } while (m);

暫無
暫無

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

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