代码之家  ›  专栏  ›  技术社区  ›  Ross McFarlane

regex:如何用$n个字符串实例替换?

  •  1
  • Ross McFarlane  · 技术社区  · 16 年前

    我想用00042098234代替表格4.2098234E-3的编号。我可以用以下方法捕获部件:

    (-?)(\d+).(\d)+e-($d+)
    

    但我不知道该怎么做,就是从一开始就重复零 $4 时代。

    有什么想法吗?

    事先谢谢, 罗斯

    理想情况下,我希望能够用textmate的find/replace功能来实现这一点,如果这有任何后果的话。I appreciate that there are better tools than RegEx for this problem, but it's still an interesting question (to me).

    2 回复  |  直到 16 年前
        1
  •  3
  •   Mewp    16 年前

    不能只在正则表达式中执行,因为替换字符串只是一个带有backreferences的字符串——不能在那里使用重复。

    在大多数编程语言中,有regex替换为callback,这是可以做到的。然而,它不是文本编辑器可以做的事情(除非它有一些脚本支持)。

        2
  •  1
  •   polygenelubricants    16 年前

    这不是应该用regex做的事情。说,你 可以 做这样的事情,但这并不真正值得付出努力:regex很复杂,而且功能有限。

    以下是替换数字的示例 [0-9] 有那么多零。

        // generate the regex and the replacement strings
        String seq = "123456789";
        String regex = seq.replaceAll(".", "(?=[$0-9].*(0)\\$)?") + "\\d";
        String repl = seq.replaceAll(".", "\\$$0");
    
        // let's see what they look like!!!
        System.out.println(repl); // prints "$1$2$3$4$5$6$7$8$9"
        System.out.println(regex); // prints oh my god just look at the next section!
    
        // let's see if they work...
        String input = "3 2 0 4 x 11 9";
        System.out.println(
            (input + "0").replaceAll(regex, repl)
        ); // prints "000 00  0000 x 00 000000000"
    
        // it works!!!
    

    正则表达式是( as seen on ideone.com )(为便于阅读而稍微格式化):

    (?=[1-9].*(0)$)?
    (?=[2-9].*(0)$)?
    (?=[3-9].*(0)$)?
    (?=[4-9].*(0)$)?
    (?=[5-9].*(0)$)?
    (?=[6-9].*(0)$)?
    (?=[7-9].*(0)$)?
    (?=[8-9].*(0)$)?
    (?=[9-9].*(0)$)?
    \d
    

    但它是如何工作的呢??

    Regex依赖于 positive lookaheads . 它匹配 \d 但在这之前,它会尝试看看 [1-9] . 如果是这样, \1 一直到输入的结尾,其中 0 已附加,以捕获 零 . 然后第二个断言检查 [2-9] 如果是这样的话, \2 一直到要获取的输入的结尾 零 等等。

    这项技术可行,但除了可爱的regex练习外,它可能没有真正的实用性。

    还要注意 11 被替换为 00 . 也就是说,每一个 1 替换为1零。可能可以将11识别为一个数字,并将其改为11个零,但这只会使regex更加复杂。