English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
部分式/記号文字「 [^ ...] ”全ての単一文字をマッチさせ、括弧は除外します。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class SpecifiedCharacters { public static void main( String args[] ) { String regex = "[^hwtyoupi]"; String input = "Hi how are you welcome to w3codebox"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int件数 = 0; while(m.find()) { 件数++; } System.out.println("試合数: "+件); } }
出力結果
試合数 21
以下のJavaプログラムはユーザーから5文字列を入力し、英文字母を含まない文字列を印刷/単語。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "^.*[^a-zA-Z].*$"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 入力文字列: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Pattern オブジェクトを作成 Pattern p = Pattern.compile(regex); System.out.println("英文字母を含まない文字列: "); for(int i=0; i<5;i++) { //Matcher オブジェクトを作成 Matcher m = p.matcher(input[i]); if(m.find()) { System.out.println(m.group()); } } } }
出力結果
入力 5 入力文字列: 1234*5 *&% サンプル テスト データ23 英文字母を含まない文字列: 1234*5 *&%