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?

More than 3 years have passed since last update.

正規表現にマッチした文字列すべてを取得したい

Posted at

必要になるたびググって、そのたびに忘れている気がするので、自分用にメモしておきたいと思います。

正規表現にマッチした文字列すべてを取得したい場合、Java8以前であれば以下のようなイディオムとなります。

String s = "111 AAA 222 BBB 333";
Pattern p = Pattern.compile("[0-9]{3}");
Matcher m = p.matcher(s);

List<String> results = new ArrayList<>();
while (m.find()) {
    results.add(m.group());
}
System.out.println(results); //=> [111, 222, 333]

Java9以降であればStreamを使って、シンプルに書くこともできます。

String s = "111 AAA 222 BBB 333";
Pattern p = Pattern.compile("[0-9]{3}");
Matcher m = p.matcher(s);

List<String> results = m.results().map(MatchResult::group).toList();
System.out.println(results);  //=> [111, 222, 333]
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?