메타 문자 "." 자바 정규식은 알파벳, 숫자 또는 특수 문자가 될 수 있는 모든 문자(단일)와 일치합니다.
예시 1
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 any character
String regex = ".";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count ++;
}
System.out.println("Given string contains "+count+" characters.");
}
} 출력
Enter a String hello how are you welcome to tutorialspoint Given string contains 42 characters.
다음 정규식을 사용하여 와 b 사이의 3개 문자를 일치시킬 수 있습니다. -
a…b
유사하게 ".*" 표현식은 n개의 문자와 일치합니다.
예시 2
다음 Java 프로그램은 사용자로부터 5개의 문자열을 읽고 b로 시작하고 그 사이에 임의의 수의 문자로 끝나는 문자열을 수락합니다.
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 = "^b.*a$";
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 input strings: ");
String input[] = new String[5];
for (int i=0; i<5; i++) {
input[i] = sc.nextLine();
}
//Creating a Pattern object
Pattern p = Pattern.compile(regex);
for(int i=0; i<5;i++) {
//Creating a Matcher object
Matcher m = p.matcher(input[i]);
if(m.find()) {
System.out.println(input[i]+": accepted");
} else {
System.out.println(input[i]+": not accepted");
}
}
}
} 출력
Enter 5 input strings: barbara boolean baroda ram raju barbara: accepted boolean: not accepted baroda: accepted ram: not accepted raju: not accepted