简体   繁体   English

groovy:拆分字符串但包含定界符

[英]groovy: split a string but include the delimiter

I want to split a string about a delimiter, but I want the delimiter to be included in the output. 我想分割有关定界符的字符串,但我希望定界符包含在输出中。 For example: 例如:

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

Is there a method that does this, or do I need to write my own? 是否有执行此操作的方法,或者我需要编写自己的方法?

Here is a method that works 这是一种有效的方法

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;
}

I don't know of a method that does this, but you could use meta-programming to add your own: 我不知道执行此操作的方法,但是您可以使用元编程来添加自己的方法:

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

There is no need for post-processing by Groovy code. 无需通过Groovy代码进行后处理。 Regex has enough power to do the task on its own. 正则表达式有足够的能力自行完成任务。 Try this regex: 试试这个正则表达式:

.+?(?=X|$)

How it works: 这个怎么运作:

  • .+? - Match non-empty sequence of characters, as little as possible. -尽可能少地匹配非空字符序列。
  • (?=X|$) - Positive lookup: After what you have just matched there is either X (your pattern) or the end of the string. (?=X|$) -正向查找:在您刚刚匹配的内容之后,将出现X (您的模式)或字符串的结尾。

In Groovy the task is now not to split the source string, but find all matches. 在Groovy中,现在的任务不是拆分源字符串,而是查找所有匹配项。

Try this code: 试试这个代码:

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

Note that I changed double quotes around the regex to single quotes, to prevent interpolation of variables. 请注意,我将正则表达式周围的双引号更改为单引号,以防止变量插值。

It prints: 它打印:

[hello, Xthere, Xmy, Xfriend]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM