如何使用Java RegEx匹配任何字符

How to match any character using Java RegEx

元字符"。" 在Java正则表达式中,匹配的任何字符(单个)都可以是字母,数字或任何特殊字符。

例子1

<!-

现场演示

->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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.");
 }
}

输出量

1
2
3
Enter a String
hello how are you welcome to tutorialspoint
Given string contains 42 characters.

您可以使用以下正则表达式匹配a和b之间的任意3个字符-

1
a…b

类似地,表达式"。*"与n个字符匹配。

例子2

随后的Java程序从用户读取5个字符串,并接受以b开头,以a结尾且中间包含任意数量的字符的字符串。

<!-

现场演示

->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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");
    }
   }
 }
}

输出量

1
2
3
4
5
6
7
8
9
10
11
Enter 5 input strings:
barbara
boolean
baroda
ram
raju
barbara: accepted
boolean: not accepted
baroda: accepted
ram: not accepted
raju: not accepted