2016-08-11 10 views
2

私はこの質問と同じ作業をgroovyとしたいと思います。Groovy null regex

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 

これは結果matchの代わりitemほぼ期待される結果を与えるが、引用符が残っを返す

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

あなたは望ましい結果plsは – injecteer

+1

なぜを提供することができますテキストを解析し、CSVパーサーなどの文字列区切り文字を認識する何かを活用しますか? –

+0

私は@tim_yatesの提案に行くだろう:ホイールを再発明しないでください。 – m0skit0

答えて

1

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 
0

です。正規表現を使用してそれらを除外するのか分からないが、結果から引用符を削除すると動作します:

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