【问题标题】:groovy: split a string but include the delimitergroovy:拆分字符串但包含分隔符
【发布时间】:2018-01-24 15:37:56
【问题描述】:

我想拆分关于分隔符的字符串,但我希望将分隔符包含在输出中。例如:

> String s = "helloXthereXmyXfriend"
> s.split("X")
["hello","Xthere","Xmy","Xfriend"]

有没有办法做到这一点,还是我需要自己写?

【问题讨论】:

    标签: string groovy


    【解决方案1】:

    这是一个有效的方法

    String[] split(String s, String regex) {
        String[] split = s.split(regex);
        String[] out = Arrays.stream(split)
            .map(x -> regex + x)
            .toArray(String[]::new);
        out[0] = split[0];
        return out;
    }
    

    【讨论】:

      【解决方案2】:

      我不知道有什么方法可以做到这一点,但你可以使用元编程来添加你自己的:

      String.metaClass.splitInclude { delimiter ->
          def tokens = delegate.split(delimiter) as List
          def result = tokens.withIndex().collect { item, index ->
                          (index) ? "${delimiter}${item}" : item 
                       } 
      }
      
      def s = "helloXthereXmyXfriend"
      def result = s.splitInclude('X')
      assert ["hello","Xthere","Xmy","Xfriend"] == result
      

      【讨论】:

        【解决方案3】:

        不需要通过 Groovy 代码进行后处理。正则表达式有足够的权力 自己做任务。试试这个正则表达式:

        .+?(?=X|$)
        

        它是如何工作的:

        • .+? - 尽可能少地匹配非空字符序列。
        • (?=X|$) - 正向查找:在您刚刚匹配的内容之后 X(您的模式)或字符串的结尾。

        在 Groovy 中,现在的任务不是拆分源字符串, 但找到所有匹配项。

        试试这个代码:

        String s = "helloXthereXmyXfriend"
        def tbl = s.findAll('.+?(?=X|$)')
        print tbl
        

        请注意,我将正则表达式周围的双引号更改为单引号, 防止变量插值。

        打印出来:

        [hello, Xthere, Xmy, Xfriend]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-13
          • 1970-01-01
          • 1970-01-01
          • 2018-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多