【问题标题】:Regex matching repeated pattern, one character followed by a whitespace正则表达式匹配重复模式,一个字符后跟一个空格
【发布时间】:2016-03-18 18:28:39
【问题描述】:

我正在尝试构建一个输入表单,它应该允许用户输入任意数量的字母,后跟一个空格(不包括最后输入的字母)。

例如:

a b c d e f= MATCHES
f g z b= MATCHES
aa bb cd efg= DOES NOT MATCH
ab c d e f g=DOES NOT MATCH

我目前有以下:

[a-zA-Z]\s+|[a-zA-Z]$

这似乎不起作用。

为什么这不起作用/我做错了什么?

【问题讨论】:

  • 您正在尝试匹配任意数量的字符,后跟一个空格。以及示例中的最后一个 ab c d e f g=DOES NOT MATCH。这让我很困惑。
  • @ccf: 一次只有一个字符。
  • @ccf:在ab中,a后面是b
  • @noob:标题应该改写成Regex matching repeated pattern, one character followed by a whitespace。只有我自己弄错了:)

标签: java regex character space


【解决方案1】:

正则表达式应该是/^([a-z]\s)+[a-z]$/i

Regex101 Demo

【讨论】:

    【解决方案2】:

    给你:

    ^(?:[a-zA-Z]\s)+[a-zA-Z]$
    # anchor it to the beginning of the line
    # non capturing group
    # with ONE letter and ONE space unlimited times
    # followed by exactly ONE letter and the end of the line ($)
    

    查看a demo on regex101.com 并确保使用MULTILINE 模式(用于锚点)。

    【讨论】:

      【解决方案3】:

      不确定您是否想以任何方式更改正则表达式,但我确实找到了一个较短的正则表达式,它可以处理单个字符后跟一个空格:

      /^\w\s$/

      【讨论】:

      • 整个字符串应该匹配。
      • 除了@noob,\s{1}\s 的冗余。
      【解决方案4】:

      你可能想试试这个模式:

      ^((?:[^ ] )+[^ ]?)$
      
      REGEX EXPLANATION:
      
      ^       # assert line start
      (       # capturing group starts
      (?:     # 1st non-capturing group starts
      [^ ]    # one non-space character
       )      # followed by a space; 1st non-capturing group ends
      +       # repeat above pattern 1 or more times
      [^ ]    # match a non-space character
      ?       # 0 or 1 time
      )       # capturing group ends
      $       # assert end of line
      

      REGEX 101 DEMO

      【讨论】:

        猜你喜欢
        • 2014-05-14
        • 2015-06-18
        • 1970-01-01
        • 2014-04-16
        • 1970-01-01
        • 2011-09-02
        • 1970-01-01
        • 1970-01-01
        • 2019-12-13
        相关资源
        最近更新 更多