English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
部分表現/記号文字「\s」は空白と同等です。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\\s"; String input = "您好,欢迎来到w"3codebox!"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } }
出力結果
マッチ数: 7
以下の例では、文字列を読み取り、その間に存在するすべての余分なスペースを削除します。
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(); //スペース(1つ以上)をマッチする正規表現 String regex = "\\s+"; //正規表現をコンパイルします Pattern pattern = Pattern.compile(regex); //マッチングオブジェクトを検索します Matcher matcher = pattern.matcher(input); //すべてのスペース文字を単一のスペースに置き換えます String result = matcher.replaceAll(" "); System.out.print("Text after removing unwanted spaces: \n"+result); } }
出力結果
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces