Java匹配线程在Java中安全吗?

正则表达式是特殊的字符序列,可以使用模式中保留的特殊语法来帮助您匹配或查找其他字符串或字符串集。它们可用于搜索,编辑或处理文本和数据。Java提供了java.util.regex包,用于与正则表达式进行模式匹配。

配对班

Matcher对象是解释模式并针对输入字符串执行匹配操作的引擎。与Pattern类一样,Matcher也没有定义公共构造函数。您可以通过调用matcher()Pattern对象上的方法来获得Matcher对象。

此类的实例不能安全地被多个并发线程使用。

示例

以下Java程序从用户接受5个字符串,并打印以数字开头的字符串。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartingwithDigit {
   public static void main( String args[] ) {
      String regex = "^[0-9].*$";
      Scanner sc = new Scanner(System.in);
      System.out.println("输入5个输入字符串: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //创建一个模式对象
      Pattern p = Pattern.compile(regex);
      System.out.println("以数字开头的字符串: ");
      for(int i=0; i<5;i++) {
         //创建一个Matcher对象
         Matcher m = p.matcher(input[i]);  
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}
输出结果
输入5个输入字符串:
sample string 1
sample string 2
11 sample string 3
22 sample string 4
43534 56353 636
以数字开头的字符串:
11 sample string 3
22 sample string 4
43534 56353 636