Is there such a thing as a wildcard character in Java?
You can use regular expressions:
if (em1.matches("524[0-9]{2}646")) {
// do stuff
}
For Java specific documentation see the Pattern
class. For some uses of regular expressions (such as in the sample above), there are shortcut methods in String
: matches()
, replaceAll()
/replaceFirst()
and split()
.
regular-expressions.info has good documentation on regular expression in general.
You can solve it easily using regular expressions:
if (em1.matches("524..646"))
for instance.
(The .
is a wildcard that stands for any character. You could replace it with \\d
if you like to restrict the wildcard to digits.)
Here is a more general variant that matches "0" against any character:
String em1 = "52494646";
String em2 = "52400646";
if (em1.matches(em2.replaceAll("0", "\\\\d"))){
System.out.println("Matches");
}
Usually you can do a combination of startsWith, endsWith, or contains to find if a String start with, ends with or contains another string. You can uses these in combination like
number.startsWith("524") && number.endsWith("646");
Using a regular expression is likely to be a better choice 95% of the time but is more expensive.