Reputation: 65
I'd like to parse a string of the form "xx;yy;zz%;tt"
into groups, where ;
is the delimiter character, and %
is the escape character. So that in this example it becomes a list of 3 elements with [xx,yy, zz;tt]
.
I know of the split method, but it doesn't take an escape character, and it seems like I need a lot of lines and temporary variables to achieve the wanted result. Is there a short way to do this, with closures ?
Upvotes: 2
Views: 89
Reputation: 200562
Using a regex with a negative lookbehind to match all semicolons not preceded by a percent sign:
static void main(String[] args) {
String test = "xx;yy;zz%;tt"
def arr = test.split(/(?<!%)\;/)
println(arr)
}
prints:
[xx, yy, zz%;tt]
You have to use the lookbehind in order to prevent characters that precede the semicolon from being captured by the regex.
Upvotes: 4