Regex Extraction in Scala

2019-09-02 09:04发布

问题:

I have a text file that has some data like this :-

1/4 cup chopped green onion
1/2 teaspoon salt
1 Tbsp cream
1 teaspoon vanilla extract

I want to write a regexp such that my data is divided into groups of 3 like below:-

'1/4' 'çup' 'chopped green onion'
'1/2' 'teaspoon' salt'
'1' 'Tbsp' 'cream'
'1' 'teaspoon' 'vanilla extract'

It means that my regex should have:

  • the first group before the first space,
  • second group between the first and second space and
  • third group after the second space till the end of line.

What is a possible way to do that?

回答1:

scala> val RecipeItem = """(\S+)\s+(\S+)\s+(.*)""".r
RecipeItem: scala.util.matching.Regex = (\S+)\s+(\S+)\s+(.*)

scala> val RecipeItem(qty, unit, ingredient) = "1/4 cup chopped green onion"
qty: String = 1/4
unit: String = cup
ingredient: String = chopped green onion


标签: regex scala