如何使用正则表达式将字符串“a b a c d a a”转换为字符串“1 b 2 c d 3 4”?
这可能吗?首选的味道是perl,但任何其他味道都是如此。
s/a/ \????? /g
答案 0 :(得分:3)
这种替代会做到。
$ perl -p -e 's/a/++$i/ge'
a b a c d a a
1 b 2 c d 3 4
答案 1 :(得分:0)
在Java正则表达式中,您使用Matcher.find()
循环,使用Matcher.appendReplacement/Tail
,目前仅使用StringBuffer
。
所以,这样的事情有效(see also on ideone.com):
String text = "hahaha that's funny; not haha but like huahahuahaha";
Matcher m = Pattern.compile("(hu?a){2,}").matcher(text);
StringBuffer sb = new StringBuffer();
int index = 0;
while (m.find()) {
m.appendReplacement(sb,
String.format("%S[%d]", m.group(), ++index)
);
}
m.appendTail(sb);
System.out.println(sb.toString());
// prints "HAHAHA[1] that's funny; not HAHA[2] but like HUAHAHUAHAHA[3]"