Skip to Content

Archived discussions are read-only. Learn more about SAP Q&A

Wildcard Matching in Java

Hello All,

I wish to match a wildcard ... how that can be achieved?

For eg:- str1 = Number of Ports;

How I can make this work -> str1.equals("Number *") ???

Please help me in fixing the above or a way out to achieve this.

I appreciate your kind help and assistance.

Thanks,

--Abhi

Former Member replied

Hi Abhi,<br />

<br />

You're looking for <i>regular expressions</i>, e.g. see the <a class="jive-link-external" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html" target="_newWindow">java.util.regex.Pattern</a> class. Basically you have two options. The simple one uses method <a class="jive-link-external" href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#matches%28java.lang.String%29" target="_newWindow">String.matches()</a>, which allows you to match patterns:

if ("Number 144".matches("Number [0-9]+")) {
	System.out.println("matched 'Number [0-9]+'");
}
if("Number of Ports".matches("Number .*")) {
	System.out.println("matched 'Number .*'");
}

Of course this is all a bit constructed, because in this case the method <a class="jive-link-external" href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#startsWith%28java.lang.String%29" target="_newWindow">String.startsWith()</a> would've done the job as well.<br />

<br />

Anyhow, if you need more flexibility you should access use the <a class="jive-link-external" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html" target="_newWindow">Pattern</a> and <a class="jive-link-external" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html" target="_newWindow">Matcher</a> class yourself instead of the condensed utility method <i>String.matches()</i> mentioned above. You would need this for example if you want to actually find out the number that is contained in the pattern, for which I've given an example below:

java.util.regex.Pattern numPat= java.util.regex.Pattern.compile("Number ([0-9]+)");
java.util.regex.Matcher numMat= numPat.matcher("Number 144");
if(numMat.matches()) {
	int num= Integer.parseInt(numMat.group(1));
	System.out.println(num);
}

<i>Regular expressions</i> are a very powerful concept; check out the documentation for further details and how to build your patterns.<br />

<br />

Cheers, harald

0 View this answer in context
Not what you were looking for? View more on this topic or Ask a question