【问题标题】:Regex: matches to new line or end of line or space in JS正则表达式:匹配 JS 中的新行或行尾或空格
【发布时间】:2022-01-23 09:41:44
【问题描述】:

我想从下面的示例字符串中提取:privacy:date

我想要一个正则表达式约束来描述 :[^:\s]+ 块(例如 :privacy:date)只能结束 由空格 \s 或换行符 \n 或字符串结尾 $ (因此我将能够在后面的步骤中制定一个逻辑分割这些块的规则)。

所以我只是将(?:$|\n|\s) 放在正则表达式的末尾,但我不适合我(下面的第三个正则表达式)。我仔细检查了它是否有效 我分别放了\s$(下面的第一个和第二个正则表达式),现在我不知道如何实现这个东西。感谢您的帮助。

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+\s/g)
(1) [' :privacy ']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+$/g)
(1) [' :date']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+(?:$|\n|\s)/g)
(1) [' :privacy ']

【问题讨论】:

  • 期待(?=$|\n|\s)
  • @ProGu 试过了,解决了!非常感谢。你能把你的答案写在下面吗?
  • @ProGu,这与(?=$|\s) 相同(因为换行符是空格)。也可以写成(?!\S)
  • 你是绝对正确的。我只是在代码中注释了一个问题并进行了最少的更改以使其正常工作。

标签: javascript regex


【解决方案1】:

在您的模式 \s:[^:\s]+\s 中,您正在匹配前导和尾随空白字符。

您可能会做的是使用右侧的(?!\S) 断言空白边界。

要获取不带前导空格字符的值,您可以使用捕获组。

\s(:[^:\s]+)(?!\S)

Regex demo

const s = "note::tmp hogehoge. :privacy :date";
const regex = /\s(:[^:\s]+)(?!\S)/g;
const result = Array.from(s.matchAll(regex), m => m[1]);
console.log(result);

【讨论】:

    【解决方案2】:

    您可以使用下面的正则表达式模式来匹配块模式:[^:\s+]+ 以空格 \s 或换行符 \n 或字符串结尾 $ 结尾

    /((:[^:\s+]+)(?:[\s\n]))|(:[^:\s+]+)(?:[\s\n])?$/gm
    
    (?:[\s\n]) - will check if the block is being followed by a space or a new line
    (:[^:\s+]+)(?:[\s\n])?$ - will check if the block is at the end of string or not.
    

    你也可以使用前瞻技术来达到同样的效果

    (:[^:\s+]+)(?=\s|\n|$)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多