I need to split string with quotes and white spaces in scala.
val str1="hello 'hi' 'how are' you"
str1.split(" ").foreach(println)
Expected o/p -
hello
'hi'
'how are'
you
words within the quote must be in output as it is!
I need to split string with quotes and white spaces in scala.
val str1="hello 'hi' 'how are' you"
str1.split(" ").foreach(println)
Expected o/p -
hello
'hi'
'how are'
you
words within the quote must be in output as it is!
This works (at least for the specified input).
val str1="hello 'hi' 'how are' you"
"('[^']+'|[^\\s]+)".r.findAllIn(str1).foreach(println)
o/p:
hello
'hi'
'how are'
you
Or this simplification, as @Mike has kindly pointed out.
"'.+?'|\\S+".r.findAllIn(str1).foreach(println)
If you also want to take escaped single quotes into account:
val str1="""hello 'hi' 'how are' you 'do\'ing?'"""
"""'([^'\\]*(?:\\.[^'\\]*)*)'|\S+""".r.findAllIn(str1).foreach(println)
Output
hello
'hi'
'how are'
you
'do\'ing?'