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

How to match the middle character in a string with regex?

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

使用 PCRE、plain Perl 或 Java regex flavors 这可能吗?

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

字符串可以是任意奇数长度。

例如,在字符串 12345 中,您可能希望获得 3,位于字符串中心的字符。

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

嗯,也许有人可以想出一个纯正则表达式的解决方案,但如果没有,您总是可以像这样动态构建正则表达式:

public static void main(String[] args) throws Exception {
    String s = "12345";
    String regex = String.format(".{%d}3.{%d}", s.length() / 2, s.length() / 2);
    Pattern p = Pattern.compile(regex);
    System.out.println(p.matcher(s).matches());
}

使用 PCRE 和 Perl(可能 Java)你可以使用:

^(?:.(?=.*?(?(1)(?=.$))(.?$)))*(.)

这会在第二个捕获组中捕获奇数长度字符串的中间字符。

Explained:

^ # 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
      (?= .$ )
    )
    # capture the end of the string +1 character, adding to  every iteration
    ( .?$ )
  )
)* # repeat
# the middle character follows, capture it
(.)