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

时间:2015-01-20 17:32:46

标签: java regex perl pcre

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

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

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

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

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

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

2 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:2)

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

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());
}
相关问题