Search code examples
javaregexregex-lookarounds

Regex expression that matches maximum of 2 asterisks and minimum of 2 chars other than asterisk


I'm trying to find the correct regular expression for matching those 2 conditions:

  1. Must contain 1 or 2 * (2 maximum, but not necessarily consecutive)
  2. Must contain at least two characters among digits and .

For exemple, following strings must match : 1*2, 1**2, *2.*. Following strings must NOT match : ab*, 1*, 1*2*.*.

So far, I've tried the following regex for the two "parts", but without any success:

  1. 1 or 2 *: \*(?![\d.]*\*[\d.]*\*[\d.]*)
  2. At least two digits or .: [\d.](?=[\*\d.]{2,})

I'm struggling finding the correct regular expressions.


Solution

  • You could assert 2 times a dot or a digit, and then match 1 or 2 times an asterix:

    ^(?=(?:[^\d.\n]*[\d.]){2})(?:[^\n*]*\*){1,2}[^\n*]*$
    

    The pattern matches:

    • ^ Start of string
    • (?= positive lookahead, assert what to the right is
      • (?:[^\d.\n]*[\d.]){2} Match 2 times optional characters other than a digit, newline or dot, and then match a digit or dot
    • ) Close the lookahead
    • (?:[^\n*]*\*){1,2} Repeat 1 or 2 times matching any character except a newline or *, and then match *
    • [^\n*]* Match optional character except a newline or *
    • $ End of string

    See a regex demo