Regular expression: replace match with index

How to convert the string "abacda a" to the string "1 b 2 cd 3 4" with a regular expression?

Is it possible? Perl is the preferred flavor, but any other will do too.

s/a/ \????? /g
+3
source share
2 answers

This replacement 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 Rate the right side as an expression.
  • g Replace globally, i.e. all occurrences.
+3
source

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

So something like this works ( see also on ideone.com ):

    String text = "hahaha that 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 funny; not HAHA[2] but like HUAHAHUAHAHA[3]"

API Links

see also

0

Source: https://habr.com/ru/post/1753853/


All Articles