Jay Taylor's notes
back to listing indexRegex and Pattern Matching in Scala - Stack Overflow
[web search]
I am not strong in regex, and pretty new to Scala. I would like to be able to find a match between the first letter of a word, and one of the letters in a group such as "ABC". In pseudocode, this might look something like:
but I don't know how to grab the first letter in Scala instead of Java, how to express the regular expression properly, nor if it's possible to do this within a case class. Any suggestions? Thanks in advance. Bruce
| |||||||||||||||||||||||||||
| |||||||||||||||||||||||||||
You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work. val Pattern = "([a-cA-C])".r word.firstLetter match { case Pattern(c) => c bound to capture group here case _ => } | |||||||||
|
As delnan pointed out, the
You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" ( | |||||||||
|
String.matches is the way to do pattern matching in the regex sense. But as a handy aside, word.firstLetter in real Scala code looks like:
Scala treats Strings as a sequence of Char's, so if for some reason you wanted to explicitly get the first character of the String and match it, you could use something like this:
I'm not proposing this as the general way to do regex pattern matching, but it's in line with your proposed approach to first find the first character of a String and then match it against a regex. EDIT: To be clear, the way I would do this is, as others have said:
Just wanted to show an example as close as possible to your initial pseudocode. Cheers! | |||||||||
|
To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:
| |||
add comment |