代码之家  ›  专栏  ›  技术社区  ›  knittl

正则表达式:用其索引替换匹配项

  •  3
  • knittl  · 技术社区  · 14 年前

    如何使用正则表达式将字符串“a b a c d a a”转换为字符串“1 b 2 c d 3 4”?

    这可能吗?首选的风格是perl,但其他任何风格也可以。

    s/a/ \????? /g
    
    2 回复  |  直到 14 年前
        1
  •  4
  •   thegeek    14 年前

    这个替代品就行了。

    $ perl -p -e 's/a/++$i/ge' 
    a b a c d a a
    1 b 2 c d 3 4
    
    • 将右侧作为表达式求值。
    • g全局替换,即所有事件。
        2
  •  0
  •   polygenelubricants    14 年前

    在javaregex中,使用 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]"
    

    API链接