1

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!

jwvh
  • 46,953
  • 7
  • 29
  • 59
ssk
  • 39
  • 3
  • Try this: [https://stackoverflow.com/a/7804472/7068014](https://stackoverflow.com/a/7804472/7068014) – nguyenhuyenag May 17 '21 at 01:55
  • You're probably going to also want to deal with the case where the string in quotes can contain quotes, no? E.g., `'here's a string'`. – Mike May 17 '21 at 03:33

3 Answers3

2

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)
jwvh
  • 46,953
  • 7
  • 29
  • 59
  • 1
    I think you're looking for `\S`. And triple quotes are usually the thing. Reluctant quantifiers are useful, too: `"""'.+?'|\S+"""`. – Mike May 17 '21 at 03:30
  • `\S` - **D'oh!** Yes, of course. _Reluctant quantifiers_ - For some reason that seldom comes to mind. I'll have to work on that. `"""` - When I get tired of double escapes I usually turn to the `raw` string interpolater. – jwvh May 17 '21 at 03:43
1

Using Guava, by adding '"com.google.guava" % "guava" % "28.1-jre"' to build.sbt, you would call the scala equivalent to the Java code:

String [] splitStringArray = Splitter.onPattern("['[:space:]]").split(inputString);

hd1
  • 30,506
  • 4
  • 69
  • 81
1

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?'

Scala demo | Regex demo

The fourth bird
  • 96,715
  • 14
  • 35
  • 52