面试题:正则表达式的匹配
题目:
实现一个函数,匹配包含‘.’和‘*’的正则表达式。
字符‘.’表示任意一个字符;‘*’表示它前面的字符可以出现任意次(含0次)
本题中,匹配是指字符串的所有字符匹配整个模式。
eg:“aaa”与模式“a.a”和“ab*ac*a”匹配,但与“aa.a”和“ab*a”均不匹配
代码:
public class Q19 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("input your string:");
String str="",regex="";
if(scanner.hasNextLine()) {
str = scanner.nextLine();
}else {
System.out.println("wrong input");
}
System.out.print("input your regex:");
if(scanner.hasNextLine()) {
regex = scanner.nextLine();
}else {
System.out.println("wrong input");
}
System.out.printf("your string is:%s\n", str);
System.out.printf("your regex is :%s\n", regex);
System.out.println(match(str,regex));
}
public static boolean match(String str,String regex) {
System.out.println("----- match ----");
regex = regex+"/";
if(regex.length()==0 || regex.charAt(0)=='*') {
System.out.print("wrong regex");
return false;
}else {
int regexLoc = 0; //
int strLoc = 0;
while(regexLoc <= regex.length()-2 && strLoc <= str.length()-1) {
// 当前正则式位置字符为'.'
if(regex.charAt(regexLoc)=='.') {
regexLoc++;
strLoc++;
// 当前正则式位置字符为ch(后不接* 则为直接对比)
}else if(regex.charAt(regexLoc+1)!='*'){
if(regex.charAt(regexLoc)!=str.charAt(strLoc)) {
return false;
}
regexLoc++;
strLoc++;
// 当前正则式位置为 字符+‘*’
}else if(regex.charAt(regexLoc+1)=='*'){
// 有该字符出现 则进入函数
if(regex.charAt(regexLoc)==str.charAt(strLoc)) {
strLoc = matchDup(regex.charAt(regexLoc),str,strLoc);
regexLoc = regexLoc +2;
// 若没有字符出现,则直接跳过匹配
}else {
regexLoc = regexLoc +2;
}
}
}
// 判断是否都到达结尾,若不是同时到达结尾则返回false,同时则返回true
if(regexLoc == regex.length()-1 && strLoc == str.length()) {
return true;
}else {
return false;
}
}
}
public static int matchDup(char c,String str,int strLoc) {
System.out.printf("c:%c,strLoc:%d\n", c,strLoc);
for(int i = strLoc;i<=str.length()-1;i++) {
if(str.charAt(i)!=c) {
return i;
}
}
return str.length();
}
}