regex - Java string matching with wildcards -
i have pattern string wild card x (e.g.: abc*).
also have set of strings have match against given pattern.
e.g.:
abf - false
abc_fgh - true
abcgafa - true
fgabcafa - false
i tried using regex same, didn't work.
here code
string pattern = "abc*"; string str = "abcdef"; pattern regex = pattern.compile(pattern); return regex.matcher(str).matches();
this returns false
is there other way make work?
thanks
just use bash style pattern java style pattern converter:
public static void main(string[] args) { string patternstring = createregexfromglob("abc*"); list<string> list = arrays.aslist("abf", "abc_fgh", "abcgafa", "fgabcafa"); list.foreach(it -> system.out.println(it.matches(patternstring))); } private static string createregexfromglob(string glob) { stringbuilder out = new stringbuilder("^"); for(int = 0; < glob.length(); ++i) { final char c = glob.charat(i); switch(c) { case '*': out.append(".*"); break; case '?': out.append('.'); break; case '.': out.append("\\."); break; case '\\': out.append("\\\\"); break; default: out.append(c); } } out.append('$'); return out.tostring(); }
is there equivalent of java.util.regex “glob” type patterns?
convert wildcard regex expression
Comments
Post a Comment