如何匹配字符串中的中间字符与正则表达式? [英] How to match the middle character in a string with regex?

查看:1203
本文介绍了如何匹配字符串中的中间字符与正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In an odd number length string, how could you match (or capture) the middle character?

PCRE,普通 Perl或Java正则表达式可以实现吗?

Is this possible with PCRE, plain Perl or Java regex flavors?

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

With .NET regex you could use balancing groups to solve it easily (that could be a good example). By plain Perl regex I mean not using any code constructs like (??{ ... }), with which you could run any code and of course do anything.

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

The string could be of any odd number length.

例如字符串 12345 你想得到 3 ,这是字符串中心的字符。

For example in the string 12345 you would want to get the 3, the character at the center of the string.

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

推荐答案

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

With PCRE and Perl (and probably Java) you could use:

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

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

which would capture the middle character of odd length strings in the 2nd capturing group.

解释

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

这篇关于如何匹配字符串中的中间字符与正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆