【问题标题】:JavaScript regular expression to match a word with any kind of punctuation at the endJavaScript 正则表达式以匹配结尾带有任何标点符号的单词
【发布时间】:2019-10-30 02:56:05
【问题描述】:

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

例如,在“我思故我在”中。我需要一个表达式来匹配“think”和“am”。

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

【问题讨论】:

    标签: javascript regex match punctuation


    【解决方案1】:

    我的猜测是您可能正在尝试编写一个表达式,可能有点类似于:

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

    如果您希望简化/修改/探索表达式,在regex101.com 的右上角面板中已对此进行了说明。如果您愿意,您还可以在this link 中观看它如何与一些示例输入匹配。


    正则表达式电路

    jex.im 可视化正则表达式:

    【讨论】:

      【解决方案2】:

      尝试反复搜索模式\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);

      【讨论】:

        猜你喜欢
        • 2016-06-21
        • 2013-01-29
        • 1970-01-01
        • 2022-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多