目标:这个代码仅局限于所展示的正规表达式判断,也就是这是一个较单一的正规表达式判断(简易版)。
既然是简易版的,所以若要修改这个正规表达式也是非常容易的,只要将二维数组中的数组修改即可。数组数据依据,该正规表达式所对应的的化简版DFA的状态装换矩阵。
如:S | a | b
0 | 1 | 2
1 | 1 | 2
2 | 1 | 2 所对应的即为{{1,2},{1,2},{1,2}}
效果:
代码:
1 package compile_design; 2 import java.util.Scanner; 3 4 public class regularExpression { 5 6 public static void main(String[] args){ 7 int [][] array = {{1,2},{1,2},{1,2},{3,3},{4,3}}; 8 System.out.println("正规表达式为: ((a|b)*|aa)*b "); 9 System.out.println("请输入你要验证的字符串:"); 10 11 Scanner input = new Scanner(System.in); 12 String str = input.next(); 13 int length = str.length(); 14 15 char ch; 16 int i = 0,j = 0, index = 0; 17 int t = 1; 18 int flag =0; 19 20 while(index < length){ 21 ch=str.charAt(index);//获取字符串首字母 22 if(ch == 'a') 23 j = 0; //0 ---a 24 if(ch == 'b') 25 j = 1; // 1 ---b 26 if(ch != 'a' && ch != 'b'){ 27 t = 0; 28 break; 29 } 30 index++; 31 i = array[i][j]; 32 } 33 34 flag = i ; 35 if(flag == 2 && t ==1){ 36 System.out.println("accept,字符串符合该正规表达式 "); 37 }else{ 38 System.out.println("reject,字符串不符合 "); 39 } 40 } 41 }