java - Regular expression to search for text using star characters -
i'm writing java application user can reduce list of strings based on filter user supplies.
so example, user enter filter such as:
abc*xyz
this means user looking strings start abc , have xyz follow (that same doing search abc*xyz*
)
another example of filter user enter is:
*def*mno*rst
this means string can start anything, must follow def, followed mno, followed rst.
how write java code able generate regular expression need figure out if strings match filter user has specified?
if converting syntax regex, "easy" way (avoiding writing lexer yourself), must remember escape string appropriately.
so if going down route, should aim quote bits aren't wildcards in syntax , join regex .*
(or .+
if want *
mean "at least 1 character). avoid incorrect results when using *
, .
, (
, )
, other regex special characters.
try like:
public pattern createpatternfromsearch(string query) { stringbuilder sb = new stringbuilder(); (string part : query.split("\\*")) { if (part.length() > 0) { sb.append(pattern.quote(part)); } sb.append(".*"); } return pattern.compile(sb.tostring()); } // ... // can use like.... matcher matcher = createpatternfromquery("*def*mno*rst").matcher(str); if (matcher.matches()) { // process matching result }
note using matcher#matches() (not find
) , leaving trailing .*
, cater syntax anchored @ start only.
Comments
Post a Comment