Task
In this challenge, you were provided a string in which you had to find the first occurrence of a three-letter word. The only constraint was that the word must only contain lower-case letters.
Solution
The first thing you had to write was a regular expression which represented three-letter words only consisting of lower-case letters and store it in a variable. Something like this:
val expressionToFind = "[a-z]{3}".r
[a-z]
specifies that the regular expression should only contain lower-case letters{3}
specifies that the regular expression should have a length of 3.
You then had to call the findFirstIn
method on the regular expression and pass it the string you wanted to search. Recall that findFirstIn
only finds the first occurrence of the specified regular expression.
val match1 = expressionToFind.findFirstIn(stringToFindExpression)
You can find the complete solution below:
You were required to write the code on line 2 and line 3.
val stringToFindExpression = "The car is red."val expressionToFind = "[a-z]{3}".rval match1 = expressionToFind.findFirstIn(stringToFindExpression)// Driver Codematch1.foreach(println)
Let’s wrap up this chapter with a quiz to test what you have learned so far.