如何在 Scala 中使用正则表达式进行模式匹配? [英] How to pattern match using regular expression in Scala?

查看:36
本文介绍了如何在 Scala 中使用正则表达式进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够找到一个单词的第一个字母与组中的一个字母(例如ABC")之间的匹配项.在伪代码中,这可能类似于:

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:

case Process(word) =>
   word.firstLetter match {
      case([a-c][A-C]) =>
      case _ =>
   }
}

但是我如何在 Scala 而不是 Java 中获取第一个字母?如何正确表达正则表达式?是否可以在 case class 中执行此操作?

But how do I grab the first letter in Scala instead of Java? How do I express the regular expression properly? Is it possible to do this within a case class?

推荐答案

您可以这样做,因为正则表达式定义了提取器,但您需要先定义正则表达式模式.我无权使用 Scala REPL 来测试这个,但这样的事情应该可以工作.

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 _ =>
}

这篇关于如何在 Scala 中使用正则表达式进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆