Scala-regular-expressions

提供:Dev Guides
移動先:案内検索

Scala-正規表現

この章では、scala.util.matchingパッケージで利用可能な Regex クラスを介してScalaが正規表現をサポートする方法について説明します。

次のサンプルプログラムを試してみてください。ステートメントから単語 Scala を見つけようとします。

import scala.util.matching.Regex

object Demo {
   def main(args: Array[String]) {
      val pattern = "Scala".r
      val str = "Scala is Scalable and cool"

      println(pattern findFirstIn str)
   }
}

上記のプログラムを Demo.scala に保存します。 このプログラムをコンパイルして実行するには、次のコマンドを使用します。

コマンド

\>scalac Demo.scala
\>scala Demo

出力

Some(Scala)

文字列を作成し、その上で* r()メソッドを呼び出します。 Scalaは暗黙的にStringをRichStringに変換し、そのメソッドを呼び出してRegexのインスタンスを取得します。 正規表現の最初の一致を見つけるには、単に findFirstIn()メソッドを呼び出します。 最初の出現のみを見つけるのではなく、一致する単語のすべての出現を検索する場合は、 findAllIn()*メソッドを使用できます。ターゲット文字列に複数のScala単語がある場合、これは一致するすべての単語。

mkString()メソッドを使用して結果のリストを連結し、パイプ(|)を使用してScalaの大文字小文字を検索し、代わりに Regex コンストラクターまたは* r()*メソッドを使用して作成できます。模様。

次のプログラム例を試してください。

import scala.util.matching.Regex

object Demo {
   def main(args: Array[String]) {
      val pattern = new Regex("(S|s)cala")
      val str = "Scala is scalable and cool"

      println((pattern findAllIn str).mkString(","))
   }
}

上記のプログラムを Demo.scala に保存します。 このプログラムをコンパイルして実行するには、次のコマンドを使用します。

コマンド

\>scalac Demo.scala
\>scala Demo

出力

Scala,scala

一致するテキストを置換する場合、* replaceFirstIn()を使用して最初の一致を置換するか、 replaceAllIn()*を使用してすべての出現箇所を置換できます。

object Demo {
   def main(args: Array[String]) {
      val pattern = "(S|s)cala".r
      val str = "Scala is scalable and cool"

      println(pattern replaceFirstIn(str, "Java"))
   }
}

上記のプログラムを Demo.scala に保存します。 このプログラムをコンパイルして実行するには、次のコマンドを使用します。

コマンド

\>scalac Demo.scala
\>scala Demo

出力

Java is scalable and cool

正規表現の形成

ScalaはJavaから正規表現構文を継承し、JavaはPerlのほとんどの機能を継承します。 ここでは、復習として十分ないくつかの例を示します-

以下は、Javaで使用可能なすべての正規表現メタ文字構文をリストした表です。

Subexpression Matches
^ Matches beginning of line.
$ Matches end of line.
. Matches any single character except newline. Using m option allows it to match newline as well.
[…​] Matches any single character in brackets.
[^…​] Matches any single character not in brackets
\\A Beginning of entire string
\\z End of entire string
\\Z End of entire string except allowable final line terminator.
re* Matches 0 or more occurrences of preceding expression.
rePLUS Matches 1 or more of the previous thing
re? Matches 0 or 1 occurrence of preceding expression.
re\{ n} Matches exactly n number of occurrences of preceding expression.
re\{ n,} Matches n or more occurrences of preceding expression.
re\{ n, m} Matches at least n and at most m occurrences of preceding expression.
a b
Matches either a or b. (re)
Groups regular expressions and remembers matched text. (?: re)
Groups regular expressions without remembering matched text. (?> re)
Matches independent pattern without backtracking. \\w
Matches word characters. \\W
Matches nonword characters. \\s
Matches whitespace. Equivalent to [\t\n\r\f]. \\S
Matches nonwhitespace. \\d
Matches digits. Equivalent to [0-9]. \\D
Matches nondigits. \\A
Matches beginning of string. \\Z
Matches end of string. If a newline exists, it matches just before newline. \\z
Matches end of string. \\G
Matches point where last match finished. \\n
Back-reference to capture group number "n" \\b
Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. \\B
Matches nonword boundaries. \\n, \\t, etc.
Matches newlines, carriage returns, tabs, etc. \\Q
Escape (quote) all characters up to \\E \\E

正規表現の例

Example Description
. Match any character except newline
[Rr]uby Match "Ruby" or "ruby"
rub[ye] Match "ruby" or "rube"
[aeiou] Match any one lowercase vowel
[0-9] Match any digit; same as [0123456789]
[a-z] Match any lowercase ASCII letter
[A-Z] Match any uppercase ASCII letter
[a-zA-Z0-9] Match any of the above
[^aeiou] Match anything other than a lowercase vowel
[^0-9] Match anything other than a digit
\\d Match a digit: [0-9]
\\D Match a nondigit: [^0-9]
\\s Match a whitespace character: [ \t\r\n\f]
\\S Match nonwhitespace: [^ \t\r\n\f]
\\w Match a single word character: [A-Za-z0-9_]
\\W Match a nonword character: [^A-Za-z0-9_]
ruby? Match "rub" or "ruby": the y is optional
ruby* Match "rub" plus 0 or more ys
rubyPLUS Match "rub" plus 1 or more ys
\\d{3} Match exactly 3 digits
\\d\{3,} Match 3 or more digits
\\d\{3,5} Match 3, 4, or 5 digits
\\D\\dPLUS No group: PLUS repeats \\d
(\\D\\d)PLUS/ Grouped: PLUS repeats \\D\d pair
([Rr]uby(, )?)PLUS Match "Ruby", "Ruby, ruby, ruby", etc.

注意-上記の文字列では、すべてのバックスラッシュが2回出現します。 これは、JavaおよびScalaでは、単一のバックスラッシュが文字列リテラルのエスケープ文字であり、文字列に現れる通常の文字ではないためです。 そのため、「\」の代わりに「\\」と記述して、文字列に単一のバックスラッシュを追加する必要があります。

次のプログラム例を試してください。

import scala.util.matching.Regex

object Demo {
   def main(args: Array[String]) {
      val pattern = new Regex("abl[ae]\\d+")
      val str = "ablaw is able1 and cool"

      println((pattern findAllIn str).mkString(","))
   }
}

上記のプログラムを Demo.scala に保存します。 このプログラムをコンパイルして実行するには、次のコマンドを使用します。

コマンド

\>scalac Demo.scala
\>scala Demo

出力

able1