Java中如何使用正则表达式匹配字符串的开头呢?
下文笔者讲述匹配字符串是否为特殊字符开头的方法分享,如下所示
正则表达式特殊字符介绍
元字符“ ^”:
匹配特定字符串的开头
即:它匹配字符串的第一个字符
例
表达式“ ^ \\ d ”:
以数字开头的字符串/行匹配。
表达式“ ^ [az]”:
匹配以小写字母开头的字符串/行
例
检测字符串是否为特殊字符开头
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestClass {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
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("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


