I would like a regular expression to match given a partial or camel cased string. For example, if the search set contains the string "MyPossibleResultString" I want to be able to match it with the likes of the following:
I'd also like to include wildcard matching, e.g.:
If it's not clear what I mean, the only example I can think of is Eclipse's "Open Type" dialog which is pretty much the exact behaviour I'm looking for. I'm not too up on the use of regexes, so I'm not sure if it matters if I'm looking for a solution in Java.
Ok so I can't really see why you would need the wildcard feature if you can already support the matching described in the first example. This is what I put together. Given a query string query, you use a regular expression to create a regular expression:
String re = "\\b(" + query.replaceAll("([A-Z][^A-Z]*)", "$1[^A-Z]*") + ".*?)\\b";
For example the query MyPosResStr will become the regex:
\\b(My[^A-Z]*Pos[^A-Z]*Res[^A-Z]*Str[^A-Z]*.*?)\\b
You then use this regex for your matching using the Matcher.find method to get something like this:
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 camel case query in the string str.
EDIT: I have added a line to handle wildcards since in my tired stupor I didn't appreciate the need for them
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With