简体   繁体   English

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

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

In an odd number length string, how could you match (or capture) the middle character? 在奇数长度字符串中,您如何匹配(或捕获)中间字符?

Is this possible with PCRE, plain Perl or Java regex flavors? 这可能与PCRE, 普通 Perl或Java正则表达式有关吗?

With .NET regex you could use balancing groups to solve it easily (that could be a good example). 使用.NET正则表达式,您可以使用平衡组轻松解决它(这可能是一个很好的例子)。 By plain Perl regex I mean not using any code constructs like (??{ ... }) , with which you could run any code and of course do anything. 通过普通的Perl正则表达式,我的意思是不使用任何代码结构,如(??{ ... }) ,您可以使用它来运行任何代码,当然也可以做任何事情。

The string could be of any odd number length. 该字符串可以是任何奇数长度。

For example in the string 12345 you would want to get the 3 , the character at the center of the string. 例如,在字符串12345你想拿到3 ,在串的中心角色。

This is a question about the possibilities of modern regex flavors and not about the best algorithm to do that in some other way. 这是一个关于现代正则表达式风格的可能性的问题,而不是以其他方式做到这一点的最佳算法。

With PCRE and Perl (and probably Java) you could use: 使用PCRE和Perl(可能还有Java),您可以使用:

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

which would capture the middle character of odd length strings in the 2nd capturing group. 这将捕获第二个捕获组中奇数长度字符串的中间字符。

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
(.)

Hmm, maybe someone can come up with a pure regex solution, but if not you could always dynamically build the regex like this: 嗯,也许有人可以提出一个纯正则表达式解决方案,但如果没有,你可以像这样动态构建正则表达式:

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM