Javaでの正規表現のメタ文字の説明
部分式/メタ文字「\s」は、同等の空白と一致します。
例1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\\s";
String input = "Hello how are you welcome to Tutorialspoint !";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
} 出力
Number of matches: 7
例2
次の例では、文字列を読み取り、それらの間の余分なスペースをすべて削除します。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match spaces (one or more)
String regex = "\\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
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
-
Javaの正規表現$(ドル)メタ文字
部分表現/メタ文字「$ 」は行の終わりに一致します。 例1 import java.util.regex.Matcher; import java.util.regex.Pattern; public class EndWith { public static void main( String args[] ) { String regex = "Tutorialspoint$"; String input = "Hi how are you welco
-
正規表現^(caret)Javaのメタ文字
部分表現/メタ文字“ ^” 行の先頭に一致します。これを正規表現で使用すると、入力文字列の後続の文と一致します。 例1 import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "^Hi how are you"; Strin