I am trying to match the Roman number from the I
to IX
with a regex.
val pattern = "(\\sI\\s|\\sII\\s|\\sIII\\s|\\sIV\\s|\\sV\\s|\\sVI\\s|\\sVII\\s|\\sVIII\\s|\\sIX\\s)".r
This can only matches the upper case. I want to ignore the case.
My test string is "Mark iii "
.
Try something like this:
"\\s(?i)(?:I{1,3}|IV|VI{0,3}|I?X)\\s"
where the (?i)
enables case insensitive matching.
Note that you might want to use word boundaries instead of space chars:
"\\b(?i)(?:I{1,3}|IV|VI{0,3}|I?X)\\b"
otherwise "Mark iii."
won't match.
Use the Java regex special construct (?i) at the front of your regex for case-insensitive matching:
val patternic = """(?i)(\sI\s|\sII\s|\sIII\s|\sIV\s|\sV\s|\sVI\s|\sVII\s|\sVIII\s|\sIX\s)""".r
Example in scala interpreter:
scala> val pattern =
"""(\sI\s|\sII\s|\sIII\s|\sIV\s|\sV\s|\sVI\s|\sVII\s|\sVIII\s|\sIX\s)""".r
pattern: scala.util.matching.Regex = (\sI\s|\sII\s|\sIII\s|\sIV\s|\sV\s|\sVI\s|\sVII\s|\sVIII\s|\sIX\s)
scala> pattern findPrefixMatchOf " VI "
res3: Option[scala.util.matching.Regex.Match] = Some( VI )
scala> pattern findPrefixMatchOf " vi "
res6: Option[scala.util.matching.Regex.Match] = None
scala> val patternic = """(?i)(\sI\s|\sII\s|\sIII\s|\sIV\s|\sV\s|\sVI\s|\sVII\s|\sVIII\s|\sIX\s)""".r
patternic: scala.util.matching.Regex = (?i)(\sI\s|\sII\s|\sIII\s|\sIV\s|\sV\s|\sVI\s|\sVII\s|\sVIII\s|\sIX\s)
scala> patternic findPrefixMatchOf " VI "
res7: Option[scala.util.matching.Regex.Match] = Some( VI )
scala> patternic findPrefixMatchOf " vi "
res9: Option[scala.util.matching.Regex.Match] = Some( vi )
I recently was provided with a very long case insensitive Java regex, I decided just not mess with it and left it as it is. It's a Java approach, but it can be used in Scala too.
import java.util.regex.Pattern
val EmailPattern = Pattern.compile(
"PatternGoesHere",
Pattern.CASE_INSENSITIVE
)
val result = EmailPattern.matcher("StringToMatch").matches()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With