English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java正則表現(RegEx)を使用して数字をマッチングする方法

メタ文字「 \\d 「または以下の式を使用して指定された文字列内の数字を一致させる: 

[0-9]

例1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //ユーザーから文字列を読み取ります}}
      System.out.println("文字列を入力してください");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\d";
      //正規表現をコンパイル
      Pattern pattern = Pattern.compile(regex);
      //マッチング検索器オブジェクト
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("桁数: ");+count);
   }
}

出力結果

文字列を入力してください
サンプルテキスト 1234 6657
桁数: 8

例2

import java.util.Scanner;
public class RegexExample {
   public static void main(String args[]) {
      //受信10桁数字の正規表現
      String regex = "\\d{10";
      System.out.println("入力値を入力してください: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      boolean result = input.matches(regex);
      if(result) {
         System.out.println("10 数字の数");
      } else {
         System.out.println("不正な入力");
      }
   }
}

出力1

入力値を入力してください:
9848022558
10 数字の数

出力2

入力値を入力してください:
5337
不正な入力
おすすめ