0

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?

4
  • 3
    Please paste the code you have tried so far Commented Jun 18, 2015 at 6:26
  • 2
    I know you are asking for Scala, and a regex. You could achieve by using split method and split each line by space. It will be converted to array, and then from that string array you could have 1/4 and cup in the 0th and 1th position. Rest strings you can again merge to form a string. just suggesting a workaround. Commented Jun 18, 2015 at 6:29
  • 4
    Show the regex you tried and why it didn't work. If you didn't attempt it yet, check the regex documentation. Commented Jun 18, 2015 at 6:30
  • to get started here is sample regex that will match line breaks regex101.com/r/pF9cV2/1. Commented Jun 18, 2015 at 6:32

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.