Okay, so I’m trying to create a regex, that will ensure these 2 things:
- String contains two ‘*’
- String ends with 3 digits
I’ve made something, which kind of works, but it does not ensure that there are only 2 *, since in these spaces between the *, it can happen that there is another *:
Pattern.compile(".*\\*.*\\*[0-9]{3}", Pattern.CASE_INSENSITIVE);
So, these .* can be anything, any amount of characters, words and so on except * because I need to ensure that there are only 2 ‘*’.
How could I do it?
>Solution :
[^*] matches anything but the * character so you could do
^(?:[^*]*\*){2}[^*]*\d{3}$
^– start of line anchor(?:– start of non-capturing group[^*]*– match zero or more non*characters\*– match on a*
)– end of non-capturing group{2}– repeat this twice[^*]*– matching only on non*characters\d{3}– end with 3 digits$– end of line anchor
In a comment you added the constraint that it should end with * followed by 3 digits. That could be done by removing [^*]* after {2}
^(?:[^*]*\*){2}\d{3}$