Java中的正则表达式是什么?

正则表达式是定义/形成用于搜索输入文本的模式的字符串。正则表达式可以包含一个或多个字符,使用正则表达式可以搜索或替换字符串。

Java提供了java.util.regex包,用于与正则表达式进行模式匹配。这个包包含三个类-

  • 模式类:此程序包的模式类是正则表达式的编译表示。为了将正则表达式与String匹配,此类提供了两种方法,即:

  • compile():此方法接受表示正则表达式的String并返回Pattern对象的一个对象。

  • matcher(): 此方法接受一个String值,并创建一个匹配器对象,该对象将给定的String与当前模式对象表示的模式匹配。

  • java.util.regex包的Matcher类是执行匹配操作的引擎。要找到匹配的值,您需要使用此类的两个方法:

  • find(): 如果当前对象表示的匹配操作成功,则此方法返回true,否则返回false。

  • group():此方法接受代表特定组的整数值,并返回在匹配操作中由指定组捕获的序列。

  • PatternSyntaxException -PatternSyntaxException对象是未经检查的异常,表示正则表达式模式中的语法错误。

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("输入输入字符串: ");
      String input = sc.nextLine();
      String regex = "[^\\p{ASCII}]";  
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);  
      //匹配字符串中的已编译模式
      Matcher matcher = pattern.matcher(input);
      //创建一个空的字符串缓冲区
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {          
          matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("Result: \n"+ sb.toString() );
   }
}
输出结果
输入输入字符串:
whÿ do we fall
Result:
wh do we fall

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
   public static void main(String[] args) {      
      Scanner sc = new Scanner(System.in);
      System.out.println("输入输入文字: ");
      String input = sc.nextLine();

      String regex = "[t]";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);  
      //匹配字符串中的已编译模式
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         int start = matcher.start();
         System.out.println(start);
      }
   }
}
输出结果
输入输入文字:
Hello how are you welcome to Nhooo
26
31
42