如何使用 Java RegEx 匹配特定字符串/行的开头

javaobject oriented programmingprogramming更新于 2024/5/5 6:04:17

元字符"^"匹配特定字符串的开头,即它匹配字符串的第一个字符。例如,

  • 表达式"^\d"匹配以数字开头的字符串/行。

  • 表达式"^[a-z]"匹配以小写字母开头的字符串/行。

示例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //从用户读取字符串
      System.out.println("输入字符串");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^[^a-zA-Z0-9//s].*";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("匹配发生");
      } else {
         System.out.println("未发生匹配");
      }
   }
}

输出

输入一个字符串
#starting with a special character
匹配发生

示例 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 = "\.$";
      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 对象
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //创建一个 Matcher 对象
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println("字符串 "+i+" 以'.'"结尾 );
         }
      }
   }
}

输出

输入 5 个字符串:
hello how are you.
where do you live
what is your name.
welcome to tutorialspoint
The Biggest Online Tutorials Library.
字符串 0 以 '.' 结尾
字符串 2 以 '.' 结尾
字符串 4 以 '.' 结尾

示例 3

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 = "^[A-Z]";
      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 对象
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //创建 Matcher 对象
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println("字符串 "+i+" 以大写字母开头");
         }
      }
   }
}

输出

输入 5 个字符串:
Sample text1
sample text2
hello how are you
Welcome to tutorialspoint
Good morning
字符串 0 以大写字母开头
字符串 3 以大写字母开头
字符串 4 以大写字母开头

相关文章


有用资源