I am trying to make a regex validation and the condition is that, whatever I have typed in 4th character it should same as 6th character from special character(- .) dash or dot
So if I have typed 4th character as – then 6th also must be – and if dot then should be dot.
Also these character can be optional. So If the string don’t have 4th character as special character(-.) then 6th also should not be have special character
Note: First 3 character must be number and 5th character also number
For example :
123-3- valid 123.4. valid 123-6. invalid 123.7- invalid 1234 valid 12-34 invalid 123.4 invalid
What I am trying is below
"""(d{3})[-.]*(d{1})[-.]${'$'}"""
Any help will be appreciated!!
Advertisement
Answer
You can write the pattern with a single optional capture group and an optional backreference, or match 4 digits.
^(?:d{3}([-.])d1|d{4})$
^
Start of string(?:
Non capture group for the alternationd{3}([-.])d1
Match 3 digits, capture one or-
or.
and then match a digit followed by the same captured char using a backreference1
|
Ord{4}
)
Close non capture group$
End of string
Or a bit shorter, matching 3 digits followed by either a digit between the same .
or -
, or just a single digit:
^d{3}(?:([-.])d1|d)$