I want to check if a string matches the following format:
"00-00"
There should be no whitespace in the String, only 2 numbers before the dash and 2 numbers after the dash.
What's the best way to do this?
You can then use p. matcher(str). matches() . See the Pattern class for more details.
Validate Using DateFormat Next, let's write the unit test for this class: DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));
Java - String matches() Method This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax: There is two types of string format() method.
You can use matches()
:
str.matches("\\d{2}-\\d{2}")
If you're going to be doing this sort of validation a lot, consider pre-compiling the regex:
Pattern p = Pattern.compile("\\d{2}-\\d{2}"); // use a better name, though
You can then use p.matcher(str).matches()
. See the Pattern
class for more details.
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