Home > other >  Regex in Java - Match anything, except '*' character
Regex in Java - Match anything, except '*' character

Time:12-09

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 '*'.

How could I do it?

CodePudding user response:

[^*] 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

CodePudding user response:

Try Following

^.*[\\*]{1}.*[\\*]{1}.*[0-9]{3}$

It ensure there are two * and end with 3 numbers

  • Related