views:

48

answers:

2

How can I transform the string "a b a c d a a" into the string "1 b 2 c d 3 4" with a regular expression?

Is this possible? Preferred flavor is perl, but any other will do too.

s/a/ \????? /g
+3  A: 

This substitution will do it.

$ perl -p -e 's/a/++$i/ge' 
a b a c d a a
1 b 2 c d 3 4
  • e Evaluate the right side as an expression.
  • g Replace globally, i.e., all occurrences.
thegeek
A: 

In Java regex, you'd use a Matcher.find() loop, using Matcher.appendReplacement/Tail, which currently takes only StringBuffer.

So, something like this works (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]"

API links

See also

polygenelubricants