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

Grails:拆分包含管道的字符串

  •  30
  • Tom  · 技术社区  · 16 年前

    我想把 String . 简单的例子:

    groovy:000> print "abc,def".split(",");
    [abc, def]===> null
    groovy:000>
    

    groovy:000> print "abc|def".split("|");
    [, a, b, c, |, d, e, f]===> null
    groovy:000>
    

    所以我的第一选择当然是换掉水管( | , )作为分隔符。

    \| )似乎没有帮助:

    groovy:000> print "abc|def".split("\|");
    ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, groovysh_parse: 1: unexpected char: '\' @ line 1, column 24.
       print "abcdef".split("\|");
                              ^
    
    1 error
    |
            at java_lang_Runnable$run.call (Unknown Source)
    groovy:000>
    
    2 回复  |  直到 13 年前
        1
  •  61
  •   Colin Hebert    16 年前

    你需要分开 \\| .

        2
  •  19
  •   mfloryan    16 年前

    您必须转义pipe,因为它在正则表达式中有特殊的含义。但是,如果使用引号,则也必须转义斜杠。基本上,有两种选择:

    asserts "abc|def".split("\\|") == ['abc','def']
    

    / 作为字符串分隔符以避免额外的转义

    asserts "abc|def".split(/\|/) == ['abc','def']
    
    推荐文章