`
huobengle
  • 浏览: 867957 次
文章分类
社区版块
存档分类
最新评论

java字符串星号、问号匹配问题解决方法

 
阅读更多

经过1通宵的思考与实验终于在2006/5/17日中午12:00点把 * ? 通配的问题解决了。

先谈谈?号(问号的处理比较简单)
用for 循环进行逐一比较就可以了。

*号的处理,就比较复杂了。在这里,我采用的是 左迭归思想进行匹配。由于鄙人文学较差,不好对代码进行解释。就请大家自行看看代码里的注释吧。(虽然少,不过关键地方都写了)

public class myString {
String str=null;
myString(String value){str=value;}

public boolean isLike(String regex)
{
if(regex.indexOf("?")!=-1)return WenHao(regex);
else if(regex.indexOf("*")!=-1)return XingHao(str,regex);
return false;
}

private boolean WenHao(String regex)
{
// ?号匹配
if(str.length()!=regex.length())return false;
for(int i=0;i<regex.length();i++)
if(str.charAt(i)!=regex.charAt(i) && regex.charAt(i)!='?')
return false;
return true;
}

private boolean XingHao(String Str,String regex)
{
// *号匹配
int Lstr=Str.length();
int Lreg=regex.length();
int x1=regex.indexOf("*");
switch(x1)
{
case -1:{
//x1=-1 regex 中没有 * 号,不需要跌归计算
if(Lstr==Lreg)
{
if(Lstr==0)return true;
for(int kk=0;kk<Lreg;kk++)//检测字符串是否匹配
if(Str.charAt(kk)!=regex.charAt(kk))return false;
return true;
}else
return false;
}
case 0:
{//x1=0 regex 中 * 号在首位
if(Lreg==1)return true;//只有一个星号,自然是匹配的,如 regex="*"
boolean right=false;
int p=0;
// *号在首位,定位 * 号 后一位
for(int k=0;k<Lstr;k++)
if(Str.charAt(k)==regex.charAt(x1+1)||regex.charAt(x1+1)=='*')
{p=k;right=true;break;}//遇到 ** 就直接 right=true;
if(right==false)return false;
else
{
if(p==Lstr)return true;
return XingHao(Str.substring(p,Lstr),regex.substring(x1+1,Lreg));
}
}
default:
{ //x1>0
for(int i=0;i<x1;i++)
if(Str.charAt(i)!=regex.charAt(i))return false;
return XingHao(Str.substring(x1,Lstr),regex.substring(x1,Lreg));
}
}
}



public static void main(String[] args) {

System.out.println("str=ABCD regex=ABC? :"+new myString("ABCD").isLike("ABC?"));
System.out.println("str=ABCD regex=A??? :"+new myString("ABCD").isLike("A???"));
System.out.println("str=ABCD regex=A?? :"+new myString("ABCD").isLike("A??"));
System.out.println("str=ABCD regex=?BC? :"+new myString("ABCD").isLike("?BC?"));
System.out.println("str=ABCD regex=*B*D :"+new myString("ABCD").isLike("*B*D"));
System.out.println("str=ABCD regex=*BCD :"+new myString("ABCD").isLike("*BCD"));
System.out.println("str=ABCD regex=*A*B*D :"+new myString("ABcCD").isLike("*A*B*D"));

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics