Pattern Matching and Regex Examples Practiced
Pattern Matching and Regex Examples Practiced
Pattern Matching
Example (Start the command line with “cmd” and write “scala” to start scala repl)
scala> println(matchPattern(1))
One
scala> println(matchPattern(2))
Two
scala> println(matchPattern(4))
None of above
Example 2: Any data type for input parameter and output parameter
scala> matchPattern(1)
res4: Any = One
scala> matchPattern(2)
res5: Any = Two
scala> matchPattern(3)
res6: Any = None of Above
scala> matchPattern(Three)
<console>:9: error: not found: value Three
matchPattern(Three)
^
scala> matchPattern("Three")
res8: Any = 3
scala> matchPattern("Four")
res9: Any = 4
scala> matchPattern("four")
res10: Any = None of Above
- import scala.util.matching.Regex
scala> val pattern = new Regex("Hello") // Using the constructor for class Regex
pattern: scala.util.matching.Regex = Hello
scala> val stringToFind = "Hello How are you? Hello Again" // String where you want to
search the pattern
stringToFind: String = Hello How are you? Hello Again
^
scala>
scala> val pattern = "Hello".r // used the method r instead of using new Regex
pattern: scala.util.matching.Regex = Hello
scala>
scala> var stringToFind = "My name is Harish and age is 10 and i study in standard 7"
stringToFind: String = My name is Harish and age is 10 and i study in standard 7
scala> val pattern = "[0-9]+".r // find all between 0 to 9 with 1 or more instance
pattern: scala.util.matching.Regex = [0-9]+
scala>
scala>
scala> pattern findFirstIn stringToFind getOrElse("No Match Found") // it will get the value as
pattern was found
res30: String = Hello
SUBEXPRESSION MATCHES
SUBEXPRESSION MATCHES
[^…] It is used to match any one character which is not in the brackets.
\\Z It is used to match end of the whole string excluding the new line, if it exists.
re{ n, m} It is used to match at least n and at most m appearances of the foregoing expression.
It is utilized to group the Regular expressions and recollects the text that are
(re) matched.
(?: re) It also groups the regular expressions but does not recollects the matched text.
\\G It is used to match the point where the endmost match overs.
It is used to match the word frontiers when it is out of the brackets and matches the
Example Description
Intermediate Stage
1. Example 1
stringToFind: String = Hello i am Able to do it, abl11 able able0
scala>
2. Example 2
scala> val pattern = "(-)?(\\d+)(\\.\\d*)?".r //listen to video at around 1 hour 40
mins//
pattern: scala.util.matching.Regex = (-)?(\d+)(\.\d*)?
scala>
scala>