【问题标题】:Match text surrounded by underscore匹配下划线包围的文本
【发布时间】:2023-01-27 04:34:43
【问题描述】:

我需要一个正则表达式来匹配:

_Sample welcome text_Sample _welcome_ _text_

但不是Sample_welcome_text

即在开始下划线之前可以有(空格或没有),在结束下划线之后可以有(空格或没有)。

我试过使用这个:

/_(?:(?! ))(.*?)[^ ]_/gmi

虽然它有效但不幸的是它匹配Sample_welcome_text

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以使用交替来以可选的空白字符后跟下划线开头,或者反过来。

    请注意,s 也可以匹配换行符。如果需要,您可以只匹配空格,或者 [^S ]* 排除换行符。

    ^s*_.*|.*_s*$
    

    Regex demo

    const regex = /^s*_.*|.*_s*$/;
    [
      "Sample welcome text_",
      "Sample _welcome_ _text_",
      "Sample_welcome_text"
    ].forEach(s =>
      console.log(`${s} --> ${regex.test(s)}`)
    )

    【讨论】:

      【解决方案2】:

      您可以使用 lookbehind 和 lookahead assertion 来搜索被下划线包围的文本,并且在开始下划线之前可以有(空格或没有/字符串开头),在结束下划线之后可以有(空格或没有/字符串结尾)。

      /(?<=[ ]+|^)_(.*?)_(?=[ ]+|$)/gmi
      

      演示:https://regex101.com/r/t41Fkm/1

      【讨论】:

        【解决方案3】:

        您可以对空格或字符串的开头/结尾使用正向后视和前视,并引用捕获组 1 中的单词:(.*?)

        const regex = /(?<=s|^)_(.*?)_(?=s|$)/gs;
        [
          "Sample welcome text_",
          "Sample _welcome_ _text_",
          "Sample_welcome_text"
        ].forEach(str => {
          let matches = [...str.matchAll(regex)].map(m => m[1]);
          console.log(str, '=>', matches);
        });

        如果你担心 Safari 不支持 lookbehind,你可以将 lookbehind 变成 capture group,并改为引用 capture group 2:

        const regex = /(s|^)_(.*?)_(?=s|$)/gs;
        [
          "Sample welcome text_",
          "Sample _welcome_ _text_",
          "Sample_welcome_text"
        ].forEach(str => {
          let matches = [...str.matchAll(regex)].map(m => m[2]);
          console.log(str, '=>', matches);
        });

        了解有关正则表达式的更多信息:https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

        【讨论】:

          猜你喜欢
          • 2021-11-07
          • 2011-01-04
          • 1970-01-01
          • 1970-01-01
          • 2013-08-22
          • 2020-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多