0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaの`String.matches()`と正規表現を理解する

0
Posted at

matches() とは

String.matches(String regex)
  • 文字列が 正規表現に完全一致 するか判定するメソッド
  • 完全一致のため、文字列の 先頭から末尾まで パターンと一致する必要がある
  • 戻り値は boolean(true / false)

正規表現 \d+ の解説

記号 意味
\d 数字1文字([0-9] と同等)
+ 直前のパターンが 1文字以上 繰り返す
\d+  =  数字が1文字以上続く文字列

動作例

"5101"  .matches("\\d+")  // → true   数字のみ
"00010" .matches("\\d+")  // → true   数字のみ
"M5101" .matches("\\d+")  // → false  英字 "M" を含む
"51 01" .matches("\\d+")  // → false  スペースを含む
"51.01" .matches("\\d+")  // → false  ピリオドを含む
""      .matches("\\d+")  // → false  空文字(+ は1文字以上のため)
" "    .matches("\\d+")  // → false  全角スペースを含む
"5101".matches("\\d+") // → false  全角数字は \d に不一致 ※

※ Javaの \d は 半角数字(0-9)のみ に一致します。全角数字(0-9)には一致しません。


matches() と find() の違い

matches() は 完全一致 のため、部分的に数字を含む文字列は false になります。

// matches() → 完全一致
"M5101".matches("\\d+")          // → false  文字列全体が \d+ でない

// find() → 部分一致(Matcherを使用)
Pattern.compile("\\d+")
       .matcher("M5101")
       .find()                    // → true   "5101" の部分が一致

文字列全体が数値のみかどうかを判定したい場合は matches() が適切です。

まとめ

メソッド 一致方法 用途
matches(regex) 完全一致 文字列全体がパターンに一致するか確認したい場合
find() 部分一致 文字列の一部にパターンが含まれるか確認したい場合
  • \d+ は 半角数字1文字以上 にマッチする正規表現
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?