【问题标题】:Regex whitespace word boundary正则表达式空格词边界
【发布时间】:2022-01-14 03:57:17
【问题描述】:

我有这个表情

\b[A-Za-z]+\b

如果我给abc@de mnop,它匹配abcdemnop,但我希望它只匹配mnop。我该怎么做?

【问题讨论】:

  • 您可以更具体地确定要匹配的内容,可以使用空格和标点符号作为分隔符而不是单词边界。
  • 您需要指定语言/工具..regex 实现因语言而异
  • 请首选Qtax answer,因为它更便于携带,因为某些正则表达式风格要求后向模式具有固定长度。

标签: regex


【解决方案1】:

\b 是一个单词边界。

所以,\b 类似于[^a-zA-Z0-9_],即\b检查word之外的任何内容

你可以改用这个正则表达式

(?<=\s|^)[a-zA-Z]+(?=\s|$)
-------- --------- ------
   |         |       |->match only if the pattern is followed by a space(\s) or end of string/line($)
   |         |->pattern
   |->match only if the pattern is preceded by space(\s) or start of string\line(^)

【讨论】:

  • @BoristheSpider 你有一个可以在 JavaScript 中运行的版本吗?
【解决方案2】:

\b 表示(?:(?&lt;!\w)(?=\w)|(?&lt;=\w)(?!\w))。这将匹配字母和@之间的位置。

你可以写:

(?<!\S)[A-Za-z]+(?!\S)

(?!\S) 等价于(?=\s|$)

【讨论】:

    【解决方案3】:

    Regex word boundary doen't match(\b) matching and whitespace

    样本中只有白色是

    abc@de mnop   
          ^
    

    试试\s([A-Za-z]+)\b

    \s 是锚点,根本不是边界

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-14
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多