Grace Grace - 1 month ago 16
Java Question

Patterns in Java

I have a set of string and I am trying to use matches.
My set of string, named patterns now has

[title@*, text@*, specification*/specificationText]
and I need to be able to convert it to
[title@(.*), text@(.*), specification(.*)/specificationText]
so that something like
specification1/specificationText
or anything else in place of 1 gets matched.

My string:
String abc = "specification1/specificationText";


Can someone please help me with how to go about doing this?

The code that I have written,

private static Boolean isMatch(String abc, Set<String> patterns) {

for (String pattern : patterns) {

Pattern r = Pattern.compile(pattern);

if (r.matcher(abc).matches()) {

return Boolean.TRUE;
}
}

return Boolean.FALSE;
}


Right now
r
takes the value,
specification*/specification
which is being compared with
specification1/specification
. So
FALSE
is being returned.

Answer

You basically need to replace * with (.*), just do it with .replace("*", "(.*)"):

Pattern r = Pattern.compile(pattern.replace("*", "(.*)"));

See the online Java demo:

Set<String> patterns = new HashSet<String>(Arrays.asList("title@*", "text@*", "specification*/specificationText"));
String abc = "specification1/specificationText";
System.out.println(isMatch(abc, patterns));
// => true

And the method:

private static Boolean isMatch(String abc, Set<String> patterns) {
    for (String pattern : patterns) {
        Pattern r = Pattern.compile(pattern.replace("*", "(.*)"));
        if (r.matcher(abc).matches()) {
            return true;
        }
    }
    return false;
}

Or even (to make it shorter, as you are not re-using the compiled regex):

private static Boolean isMatch(String abc, Set<String> patterns) {
    for (String pattern : patterns) {
        if (abc.matches(pattern.replace("*", "(.*)"))) {
            return true;
        }
    }
    return false;
}
Comments