There is a sentence: "I was born 08/02/1996. And my brother is 09/09/2000". If the string contains a number, month and year, return true; if not, then false. Here is my code. In regular expressions, I am very weak. What needs to be fixed in the second line?

public static void date(String s) { Pattern p = Pattern.compile("/([0-2]\\d|3[01])\\.(0\\d|1[012])\\.(\\d{4})/"); Matcher m = p.matcher(s); boolean b = m.matches(); System.out.println(b); } 

    1 answer 1

    At a minimum, the problem in your code is that you need to check whether there is another line in one line (corresponding to the specified regular expression), while calling the matches() method, you check the equality of the lines.

    I would implement it like this:

     String s = "Я родился 02.08.1996. А мой брат 09.03.2000"; Pattern p = Pattern.compile("[\\d]{2}.[\\d]{2}.[\\d]{4}"); Matcher m = p.matcher(s); boolean b = m.find(); System.out.println(b); 

    UPD . Learn more about the regular schedule [\\d]{2}.[\\d]{2}.[\\d]{4} :

    • [\\d]{2} - two numeric characters;
    • . - point;
    • [\\d]{2} - two numeric characters;
    • . - point;
    • [\\d]{4} - four numeric characters.

    UPD 2 . Regular to check the date format DD.MM.YYYY :

     ^(0?[1-9]|[12][0-9]|3[01]).(0?[1-9]|1[012]).\d{4}$ 
    • Can you explain the construction is built - Vlad Kesia
    • @ VladKesia, See UPD . - post_zeew
    • And if I want to put a limit, for example, on the number of months, then I need to write it down to this part [\\ d] {2} - Vlad Kesya
    • @ VladKesya, What is the restriction? - post_zeew
    • @posr_zeew, Well, see for example the user enters that he was born on 37.14.2000. I just think it makes sense to do such a check - Vlad Kesya 6:49 PM