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

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

メタ文字「 \\ D非数字文字の一致を検出します。

例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("Enter a String");
      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);
   }
}

出力結果

文字列を入力してください
サンプルテキスト 2425 36
非数字-数字文字 13

例2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //正規表現が受け入れます5文字の単語
      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("入力が一致しました");
      }
      else {
         System.out.println("不正な入力");
      }
   }
}

出力1

入力値を入力してください:
サンプル abc
入力が一致しました

出力2

入力値を入力してください:
サンプル1234
不正な入力
おすすめ