正規表現\tJavaのメタ文字
部分表現/メタ文字「\ t 」はタブスペースと一致します。
例1
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 = "\\t";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count ++;
}
System.out.println("Number of tab spaces: "+count);
}
} 出力
Enter a string: This is a sentence with tab spaces Number of tab spaces: 6
例2
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 = "\\t";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
String result = "";
while(m.find()) {
result = m.replaceAll(" ");
}
System.out.println("Result: "+result);
}
} 出力
Enter a string: This is a sentence with tab spaces Result: This is a sentence with tab 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