正则表达式替换为匹配的计数 [英] Regex replace with the count of the match

查看:111
本文介绍了正则表达式替换为匹配的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用匹配的数字/索引替换匹配。

I would like to replace a match with the number/index of the match.

在java正则表达式中有没有办法知道当前匹配的是哪个匹配号,所以我可以使用 String.replaceAll(正则表达式,替换)

Is there way in java regex flavour to know which match number the current match is, so I can use String.replaceAll(regex, replacement)?

示例:替换 [AZ] 与其本身及其索引:

Example: Replace [A-Z] with itself and its index:

Input:  fooXbarYfooZ
Output: fooX1barY2fooZ3

即此电话:

"fooXbarXfooX".replaceAll("[A-Z]", "$0<some reference to the match count>");

应该返回fooX1barY2fooZ3



注意:我正在寻找可以执行此操作的替换字符串(如果存在)。


Note: I'm looking a replacement String that can do this, if one exists.



请不要提供涉及循环或类似代码的答案。


我会接受最优雅的答案(即使它使用循环)。目前没有答案

实际工作。

I'll accept the most elegant answer that works (even if it uses a loop). No current answers
actually work.

推荐答案

Java正则表达式不支持对计数的引用匹配,所以这是不可能的。

Java regex does not support a reference to the count of the match, so it is impossible.

这篇关于正则表达式替换为匹配的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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