Qta*_*tax 9 java regex perl pcre
在奇数长度字符串中,您如何匹配(或捕获)中间字符?
这可能与PCRE,普通 Perl或Java正则表达式有关吗?
使用.NET正则表达式,您可以使用平衡组轻松解决它(这可能是一个很好的例子).通过普通的Perl正则表达式,我的意思是不使用任何代码构造(??{ ... }),使用它可以运行任何代码,当然也可以做任何事情.
该字符串可以是任何奇数长度.
例如,在字符串中,12345您需要获取3字符串中心的字符.
这是关于现代正则表达式风格的可能性的问题,而不是以其他方式做到这一点的最佳算法.
使用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)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2685 次  |  
        
|   最近记录:  |