Grails, Groovy - tokenize() splitting a comma and whitespace together

I have a Grails project that gets list of input from a form. I used an autocomplete jQuery UI and lists courses like English, Math, Science, Social Studies,. When I use the tokenize(', ') method, it splits Social Studies. The list becomes [English, Math, Science, Social, Studies] If I use tokenize(',') it does not split Social Studies but puts null at the end like [English, Math, Science, Social Studies, null]

def save(Student studentInstance) { .... def courseInputList = params.course.tokenize(', ') for (item in courseInputList){ def courseID = Course.findByCourseLike(item) StudnetCourse.link(studentInstance,courseID) } .... } 

How can I have the tokenize() delimeter be exactly ,(one whitespace), but either , or (one whitespace). I hope what I'm trying to explain makes sense.

Thank you in advance.

(I have it, for now, that javascript doesn't put a whitespace after a comma. It works fine with one delimeter. )

2

2 Answers

Use split instead

params.course = params.course?.split(', ')?: [] params.course.each{ item -> def courseID = Course.findByCourseLike(item) StudnetCourse.link(studentInstance,courseID) } 
4

Since you have no control over the String input, which gets a trailing comma at the end, I suggest you do some processing of the input first before tokenization or splitting.

Assuming your input string is input,

def input = params.course 

you can either use slicing,

def processedString = input.endsWith(',') ? input[0..input.size() - 1] : input 

or string subtraction using regular expression,

def processedString = input - ~/,\s*$/ 

which will remove the trailing comma. The only difference is that, with the string subtraction, the regex also checks for any trailing white spaces after the comma so it's a lot more flexible.

With the trailing comma gone, you can do tokenization or splitting. I suggest you use ',' to do so and just trim in the resulting list of outputs to remove the spaces.

def courses = processedString.split(',').collect { it.trim() } 

So the resulting code would be:

def processedString = params.course - ~/,\s*$/ def courses = processedString.split(',').collect { it.trim() } courses.each { course -> //do what you want to do with course } 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like