Java string asterisk, question mark matching problem solving method
Source: Internet
Author: User
Let's talk first. Number (the question mark is handled fairly simply)
Use a For loop to compare each.
* The processing of the number, it is more complicated. Here, I am using the left-fold idea to match. Because of my poor literature, it is not good to explain the code. Please take a look at the comments in the code. (although few, but key places have been written)
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)
{
Match number
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)
{
* Number Matching
int Lstr=str.length ();
int Lreg=regex.length ();
int X1=regex.indexof ("*");
Switch (x1)
{
case-1:{
X1=-1 regex does not have the * number, does not need to fall to calculate
if (Lstr==lreg)
{
if (lstr==0) return true;
for (int kk=0;kk<lreg;kk++)//detect string match
if (Str.charat (KK)!=regex.charat (KK)) return false;
return true;
}else
return false;
}
Case 0:
{//x1=0 regex * number in the first place
if (lreg==1) return true;//only one asterisk, nature is matched, such as regex= "*"
Boolean right=false;
int = =;
* Number in the first place, locate the * number one
for (int k=0;k<lstr;k++)
if (Str.charat (k) ==regex.charat (x1+1) | | Regex.charat (x1+1) = = ' * ')
{p=k;right=true;break;} Encounter * * Directly 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));
}
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.