user1919249
user1919249

Reputation: 377

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]

Upvotes: 2

Views: 544

Answers (2)

Michael Easter
Michael Easter

Reputation: 24468

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

Upvotes: 1

Gergely Toth
Gergely Toth

Reputation: 6977

Returning the match instead of item gives nearly the expected result but the quotes remain. Don't know how to exclude them using regexp but removing the quotes from the result works:

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

Upvotes: 0

Related Questions