Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for: 6 digits or 0-6 signs (digits or stars) with at least one star

Tags:

regex

How to write regex to validate this pattern?

123456 - correct
*1 - correct
1* - correct
124** - correct
*1*2 - correct
* - correct
123456* - incorrect (size 7)
12345 - incorrect (size 5 without stars)

tried:

^[0-9]{6}$|^(([0-9]){1,6}([*]){1,5}){1,6}+$

But it allows to have more than 6 numbers and don't allow for star to be before number. There is no minimum/maximum count of "*" sign (but max count for all signs is 6).

like image 292
Marcin Avatar asked Dec 02 '22 23:12

Marcin


1 Answers

Here you go:

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

Here is what it does:

^            <-- Start of the string (we don't want to capture more than that)
  (?:          <-- Start a non captured group (it will be used to do the "or" part)
    \d{6}          <-- 6 digits, nothing more
    |            <-- OR
    (?=.*\*)       <-- Look ahead for a '*' (you could replace the first * with {0,5})
    [\d*]          <-- digits or '*'
    {1,6}          <-- repeated one to six times (we know from the look ahead that there will be at least one '*'
    |            <-- OR (nothing)
  )            <-- End the non capturing group
$            <-- End of the string

I'm not quite sure if you want the empty case (but you said 0 to 6), if you actually want 1 to 6 just remove the last |

like image 182
Colin Hebert Avatar answered Dec 20 '22 16:12

Colin Hebert