Scala 正则表达式忽略大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17930774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:33:45  来源:igfitidea点击:

Scala regex ignorecase

regexscala

提问by qingpan

I am trying to match the Roman number from the Ito IXwith a regex.

我想从罗马号相匹配I,以IX用正则表达式。

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 ".

我的测试字符串是"Mark iii ".

回答by Bart Kiers

Try something like this:

尝试这样的事情:

"\s(?i)(?:I{1,3}|IV|VI{0,3}|I?X)\s"

where the (?i)enables case insensitive matching.

其中(?i)启用不区分大小写的匹配。

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.

否则"Mark iii."将不匹配。

回答by lreeder

Use the Java regex special construct(?i) at the front of your regex for case-insensitive matching:

在正则表达式前面使用 Java 正则表达式特殊构造(?i) 进行不区分大小写的匹配:

val patternic = """(?i)(\sI\s|\sII\s|\sIII\s|\sIV\s|\sV\s|\sVI\s|\sVII\s|\sVIII\s|\sIX\s)""".r

val 模式 = """(?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 解释器中的示例:

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 )

回答by MaxNevermind

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.

我最近收到了一个很长的不区分大小写的 Java 正则表达式,我决定不要弄乱它并保持原样。这是一种 Java 方法,但它也可以在 Scala 中使用。

import java.util.regex.Pattern

val EmailPattern = Pattern.compile(
  "PatternGoesHere", 
  Pattern.CASE_INSENSITIVE
)
val result = EmailPattern.matcher("StringToMatch").matches()