简体   繁体   中英

How to handle (\w+)+? regex as string list in pattern matching scala

I am developing a scala project. In fact, I should create some commands like CLI commands. For example: exit, help, load filename, find name. And I want to handle these commands with regex pattern matching. But I have some problems. If string is "load filename", the filename can be handle. However if string is "load filename1 filename2", I can not handle filename1 and filename2 together.

My code is as follow:

val help = """help""".r
val exit = """exit""".r
val load = """load(\s+\w+)+?\s*""".r
val find = """findbyName(\s+\w+)+?\s*""".r

val input = "load filename1"
 input match {
    case help() => println("help")
    case exit() => println("exit)
    case load(filename) => println(filename)
    case find(name) => println(name)
    case _ => println "error"
  }

***********************
console: filename1

I want to print all filename if n filenames. How can I proceed?

I think you can first capture filenames with:

load\s((?:\w+\s?)+)

DEMO

and then split() captured group with \\s , " " or other character you find valid in your project.

I'm not sure how it works in Scala, but I would also try with:

load\s(\w+\s?)|(?<=\G)(\w+)\s?

DEMO

witch use \\G boudary, which match only after previus match. I think you would be able to get all filenames separetly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM