Regex object
We can use regular expressions using the scala.util.matching.Regex class. To construct a Regex object, use the r method of the String class:
val numPattern = "[0-9] +". r
If the regular expression contains backslashes or quotation marks, then the best use of the "original" string syntax "" "..." "":
val positiveNumPattern = "" "^ [1-9] \ d * $" ""
If you use the above regular expression in Java, you should use the following (escaped):
val positiveNumPattern = "^ [1-9] \\ d * $"
Scala is probably easier to read than it's used in Java.
FindAllIn
The findAllIn method returns an iterator that traverses all matches. It can be used in a for loop:
val str = "ab 27 c 6 d 1" val numPattern = "[0-9] +". r for (matchingStr <- numPattern.findAllIn (str)) {println (matchingStr)}
Or Iterator into an array:
val str = "ab 27 c 6 d 1" val numPattern = "[0-9] +". r val matches = numPattern.findAllIn (str) .toArray // Array (27,6,1) 3. findPrefixOf
To check if the prefix of a string matches, you can use the findPrefixOf method:
val str = "3 ab 27 c 6 d 1" val str2 = "ab 27 c 6 d 1" val numPattern = "[0-9] +". r val matches = numPattern.findPrefixOf (str) val matches2 = numPattern. findPrefixOf (str2) println (matches) // Some (3) println (matches2) // None 4. replaceFirstIn replaceAllIn
You can use the following command to replace the first match or replace all matches:
val str = "3 ab 27 c 6 d 1" val numPattern = "[0-9] +". r val matches = numPattern.replaceFirstIn (str, "*") val matches2 = numPattern.replaceAllIn (str, "*" ) println (matches) // * ab 27 c 6 d 1 println (matches2) // * ab * c * d * 5. Regular expression set
Grouping allows us to easily retrieve regular expression sub-expressions. Put parentheses around the subexpressions you want to extract:
val str = "3 a" val numPattern = "([0-9] +) ([az] +)". r val numPattern (num, letter) = str println (num) // 3 println a
The above code sets num to 3 and letter to a
If you want to extract the contents of a group from multiple matches, you can use the following command:
val str = "3 abc 4 f" val numPattern = "([0-9] +) ([az] +)". r for (numPattern (num, letter) <- numPattern.findAllIn (str)) {println num + "---" + letter)} // 3 --- a // 4 --- f