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!!
You can write the pattern with a single optional capture group and an optional backreference, or match 4 digits.
^(?:\d{3}([-.])\d\1|\d{4})$
^
Start of string (?:
Non capture group for the alternation
\d{3}([-.])\d\1
Match 3 digits, capture one or -
or .
and then match a digit followed by the same captured char using a backreference \1
|
Or\d{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}(?:([-.])\d\1|\d)$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.