【发布时间】:2019-10-30 02:56:05
【问题描述】:
我正在尝试使用正则表达式将句子翻译成 Pig-Latin。我需要选择末尾带有任何标点符号的单词,以便我可以以不同的方式处理这些情况。
例如,在“我思故我在”中。我需要一个表达式来匹配“think”和“am”。
我尝试了各种方法,例如word.match(/\w+[!?.:;]$/) 没有结果。
【问题讨论】:
标签: javascript regex match punctuation
我正在尝试使用正则表达式将句子翻译成 Pig-Latin。我需要选择末尾带有任何标点符号的单词,以便我可以以不同的方式处理这些情况。
例如,在“我思故我在”中。我需要一个表达式来匹配“think”和“am”。
我尝试了各种方法,例如word.match(/\w+[!?.:;]$/) 没有结果。
【问题讨论】:
标签: javascript regex match punctuation
我的猜测是您可能正在尝试编写一个表达式,可能有点类似于:
\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 的右上角面板中已对此进行了说明。如果您愿意,您还可以在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);
【讨论】: