如何匹配字符串中的中间字符与正则表达式?

Qta*_*tax 9 java regex perl pcre

在奇数长度字符串中,您如何匹配(或捕获)中间字符?

这可能与PCRE,普通 Perl或Java正则表达式有关吗?

使用.NET正则表达式,您可以使用平衡组轻松解决它(这可能是一个很好的例子).通过普通的Perl正则表达式,我的意思是不使用任何代码构造(??{ ... }),使用它可以运行任何代码,当然也可以做任何事情.

该字符串可以是任何奇数长度.

例如,在字符串中,12345您需要获取3字符串中心的字符.

这是关于现代正则表达式风格的可能性的问题,而不是以其他方式做到这一点的最佳算法.

Qta*_*tax 8

使用PCRE和Perl(可能还有Java),您可以使用:

^(?:.(?=.*?(?(1)(?=.\1$))(.\1?$)))*(.)
Run Code Online (Sandbox Code Playgroud)

这将捕获第二个捕获组中奇数长度字符串的中间字符.

解释:

^ # beginning of the string
(?: # loop
  . # match a single character
  (?=
    # non-greedy lookahead to towards the end of string
    .*?
    # if we already have captured the end of the string (skip the first iteration)
    (?(1)
      # make sure we do not go past the correct position
      (?= .\1$ )
    )
    # capture the end of the string +1 character, adding to \1 every iteration
    ( .\1?$ )
  )
)* # repeat
# the middle character follows, capture it
(.)
Run Code Online (Sandbox Code Playgroud)

  • 或者使用正确的量词:`^(?:.(?=.+((?(1).\ 1 |.))$))*\K. (3认同)
  • @jaytea:你也很近,[`^(?:.(?=.*?(.\ 1?$)))*?\ K.(?=\1?$)`](https:// regex101.com/r/Z1VVTF/1/) (3认同)
  • 我发现了这个:`^(?:.(?=.*((?(1).\ 1 |.))$))*\K.这并没有太大的不同. (2认同)
  • @CasimiretHippolyte,很好的解决方案,+ 1!你应该发布它. (2认同)