Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex in Java – Match anything, except '*' character

Okay, so I’m trying to create a regex, that will ensure these 2 things:

  1. String contains two ‘*’
  2. 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 ‘*’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Demo


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}$

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading