Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string matches a specific format?

Tags:

java

string

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?

like image 945
maysi Avatar asked Aug 15 '13 18:08

maysi


People also ask

How do you check if a string matches a specific format in Java?

You can then use p. matcher(str). matches() . See the Pattern class for more details.

How do you validate a date in YYYY MM DD format in Java?

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"));

How do you match a string in Java?

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).

What is string format in Java?

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.


1 Answers

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.

like image 110
arshajii Avatar answered Oct 07 '22 17:10

arshajii