As stated in the comments below you are using .matches
which returns true if the whole string can be matched.
In your pattern ([0-9]{2}[/-])?([0-9]{2}[/-])?([0-9]{4})
it would also match only 4 digits as the first 2 groups ([0-9]{2}[/-])?([0-9]{2}[/-])?
are optional due to the question mark ?
leaving the 3rd group ([0-9]{4})
able to match 4 digits.
What you might do instead is to use an alternation to either match a date like format where the first 2 parts including the delimiter are optional. Or match 3 times 4 digits.
.*?(?:(?:[0-9]{2}[/-]){2}[0-9]{4}|[0-9]{4}(?:\h[0-9]{4}){2}).*
Explanation
.*?
Match any character except a newline non greedy
(?:
Non capturing groupo
(?:[0-9]{2}[/-]){2}
Repeat 2 times matching 2 digits and /
or -
[0-9]{4}
Match 4 digits
|
Or
[0-9]{4}
Match 4 digits
(?:\\h[0-9]{4}){2}
Repeat 2 times matching a horizontal whitespace char and 4 digits
)
Close non capturing group
.*
Match 0+ times any character except a newline
Regex demo | Java demo
For example
List<String> list = Arrays.asList(
new String[]{
"10/02/1992 or 1992",
"10/02/1992",
"10/1992",
"02/1992",
"1992",
"1234 5694 7487"
}
);
String regex = ".*?(?:(?:[0-9]{2}[/-]){2}[0-9]{4}|[0-9]{4}(?:\\h[0-9]{4}){2}).*";
for (String str: list) {
if (str.matches(regex)){
System.out.println(str);
}
}
Result
10/02/1992 or 1992
10/02/1992
1234 5694 7487
Note that in your first pattern I think you mean \\s
instead of //s
.
The \\s
will also match a newline. If you want to match a single space you could just match that or use \\h
to match a horizontal whitespace character.