user1919249 user1919249 - 3 months ago 19
Groovy Question

Groovy null regex

I would like to do the same task as this question but with groovy.

REGEX: How to split string with space and double quote

def sourceString = "18 17 16 \"Arc 10 12 11 13\" \"Segment 10 23 33 32 12\" 23 76 21"

def myMatches = sourceString.findAll(/("[^"]+")|\S+/) { match, item -> item }

println myMatches


This is the result

[null, null, null, "Arc 10 12 11 13", "Segment 10 23 33 32 12", null, null, null]

Answer

Consider the following, which uses the Elvis operator:

def sourceString = '18 17 16 "Arc 10 12 11 13" "Segment 10 23 33 32 12" 23 76 21'

def regex = /"([^"]+)"|\S+/

def myMatches = sourceString.findAll(regex) { match, item -> 
    item ?: match 
}

assert 8 == myMatches.size()

assert 18 == myMatches[0] as int
assert 17 == myMatches[1] as int
assert 16 == myMatches[2] as int
assert "Arc 10 12 11 13" == myMatches[3]
assert "Segment 10 23 33 32 12" == myMatches[4]
assert 23 == myMatches[5] as int
assert 76 == myMatches[6] as int
assert 21 == myMatches[7] as int
Comments