如何匹配字符串中的中间字符与正则表达式?
在奇数长度字符串中,您如何匹配(或捕获)中间字符?
这可能与PCRE, 普通 Perl或Java正则表达式有关吗?
使用.NET正则表达式,您可以使用平衡组轻松解决它(这可能是一个很好的例子)。 通过普通的Perl正则表达式,我的意思是不使用任何代码结构,如(??{ ... })
,您可以使用它来运行任何代码,当然也可以做任何事情。
该字符串可以是任何奇数长度。
例如,在字符串12345
您需要获取字符串中心的3字符。
这是关于现代正则表达式风格的可能性的问题,而不是以其他方式做到这一点的最佳算法。
使用PCRE和Perl(可能还有Java),您可以使用:
^(?:.(?=.*?(?(1)(?=.\1$))(.\1?$)))*(.)
这将捕获第二个捕获组中奇数长度字符串的中间字符。
解释 :
^ # 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 (.)
嗯,也许有人可以提出一个纯正则表达式解决方案,但如果没有,你可以像这样动态构建正则表达式:
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()); }