Reputation: 1589
Test code here. I want to augment my current regex to split on commas
String test = "This Is ,A Test"
println(test)
String noSpace = test.replaceAll("\\s","")
println(noSpace)
String[] words = noSpace.split("[^a-zA-Z0-9'-.]+")
words.each {
println(it)
}
This produces the output
This Is ,A Test
ThisIs,ATest
ThisIs,ATest
Where I want it to produce the output
This Is ,A Test
ThisIs,ATest
ThisIs
ATest
Any thoughts? Thanks!
Upvotes: 0
Views: 91
Reputation: 2423
Cite from javadoc
Note that a different set of metacharacters are in effect inside a character class than outside a character class. For instance, the regular expression . loses its special meaning inside a character class, while the expression - becomes a range forming metacharacter.
So you need to escape the dash:
String[] words = noSpace.split("[^a-zA-Z0-9'\\-.]+");
Upvotes: 2
Reputation: 3753
To split based on comma, simply use
String[] words = noSpace.split(",");
Upvotes: 2