Java – regular expressions that match strings from partial or hump cases?
Given a partial or humped string, I want a regular expression match For example, if the search set contains the string "mypossibleresultstring", I want to be able to match it with the following:
> MyPossibleResultString > MPRS > MPRString > MyPosResStr > M.
I also want to include wildcard matching, for example:
>MYP * rstring > * posresstring > my * string
If I don't know what I mean, the only example I can think of is eclipse's "open type" dialog, which is almost the exact behavior I'm looking for I don't know much about using regular expressions, so if I'm looking for a Java solution, I'm not sure it's important
Solution
Well, if you already support the matching described in the first example, I really don't understand why you need the wildcard function This is what I put together Given a query string, you use regular expressions to create regular expressions:
String re = "\\b(" + query.replaceAll("([A-Z][^A-Z]*)","$1[^A-Z]*") + ".*?)\\b";
For example, the query myposresstr will become a regular expression:
\\b(My[^A-Z]*Pos[^A-Z]*Res[^A-Z]*Str[^A-Z]*.*?)\\b
Then use this regular expression to use matcher Match the find method to get the following:
public static String matchCamelCase(String query,String str) { query = query.replaceAll("\\*",".*?"); String re = "\\b(" + query.replaceAll("([A-Z][^A-Z]*)","$1[^A-Z]*") + ".*?)\\b"; System.out.println(re); Pattern regex = Pattern.compile(re); Matcher m = regex.matcher(str); if (m.find()) { return m.group(); } else return null; }
This will return the first match to your hump case query in the string str
Editor: I've added a line to deal with wildcards, because in my tired coma, I don't understand their necessity