JavaScript 正则表达式以匹配结尾带有任何标点符号的单词

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

我正在尝试使用正则表达式将句子翻译成 Pig-Latin。我需要 select 单词末尾带有任何标点符号,以便我可以不同地处理这些情况。

例如,在"I think, therefore I am."中我需要一个表达式来匹配"think,"和"am."

我尝试了各种方法,例如word.match(/\w+[!?.:;]$/)没有结果。

我猜你可能想写一个表达式,可能有点类似于:

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

Demo

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}`);
    });
}


如果您希望 simplify/modify/explore 表达式,regex101.com. If you'd like, you can also watch in this link 的右上面板已对其进行说明,它将如何匹配一些示例输入。


正则表达式电路

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);