I have a string which has a pattern, say "xxx.xxx".
So first three are digits, then a . and then 3 more digits.
I want to check if first digit is always 3, and next 2 can be any digits except 30 and 40, rest can be anything.
My regex attempt is:
"3[^34][0-9]."
But it doesn't seem to work. Which part here is wrong?
CodePudding user response:
Try this: ^3(?!30|40)\d{2}\.\d{3}$
Test regex here: https://regex101.com/r/iCtKnB/1
^ matches the start of string
3 matches the number 3
(?!30|40) checks if the next two numbers are not either 30 or 40
\d{2} matches two digits if they are not 30 or 40
\. matches period
\d{3} matches the next three digits
$
Basically this will match any number of your pattern which begins with 3 not followed by 30 or 40 then a dot, followed by another three digits.
In your regex: "3[^34][0-9]."
- 3 > This checks the number starts with 3
- [^34] > then the Next digit is not 3 or 4
- [0-9] > followed by one digits which can be 0 to 9
- . > followed by any other char that is not white spaces
So your requirements were not being checked in this regex.
CodePudding user response:
In case lookaheads are not supported you can use:
^3(?:[0-25-9][0-9]|[34][1-9])\.[0-9]{3}$
CodePudding user response:
You may try this:
^3(?!30|40)\d{2}\.\d{3}$
Explanation:
^
asserts position at start of a line3
starts with 3(?!30|40)
negative look ahead to see the following two characters do not match 30 or 40 if found successful then\d{2}
ensures any two digits.\.
means a dot\d{3}
means 3 digits$
asserts position at the end of a line