Utsav
Utsav

Reputation: 145

Scala Regex: matching a non single character input

For instance the function:

val reg = "[^ ]".r

takes in an input that would match with every character except for the empty space character.

and:

def matchReg(line: String): List[String] = reg.findAllIn(line).toList

Converts the input into a list.

However how would I edit this so that it would match with a non-single character input. Since it seems as though this splits the input such as "14" into "1" and "4" when the values of the regular expression are turned into a list. If the input is "14" I want it to output "14" rather than it being split. Thank you.

EDIT: I have written test cases to explain the type of output I am looking for

"The match" should "take list" in {
    assert(matchReg("(d e f)") == List("(", "d", "e", "f", ")"))
  }

  it should "take numbers" in {
    assert(matchReg("(12 45 -9 347 4)") == List("(", "12", "45", "-9", "347", "4", ")"))
  }

  it should "take operators" in {
    assert(matchReg("(- 7 (* 8 9))") == List("(", "-", "7", "(", "*", "8", "9", ")", ")"))
  }

With the following case, "take list" and "take operators" passes successfully if I use:

val reg = "[^ ]".r

However "take numbers" does not pass since numbers such as "347" are being split into "3" "4" and "7", when I want them to register as one single number.

Upvotes: 0

Views: 62

Answers (1)

nap.gab
nap.gab

Reputation: 451

This should work for you

val reg = """[^ \(\)]+|\(|\)""".r 

You should add some other alternatives if you want to support also [ ] , { } or other operators

@ matchReg("(d e f)") 
res8: List[String] = List("(", "d", "e", "f", ")")

@ matchReg("(12 45 -9 347 4)") 
res9: List[String] = List("(", "12", "45", "-9", "347", "4", ")")

@ matchReg("(- 7 (* 8 9))") 
res10: List[String] = List("(", "-", "7", "(", "*", "8", "9", ")", ")")

Upvotes: 2

Related Questions