Home > database >  Regex must start with specific number, must contain 2 hyphens and must end with 4 digit numbers
Regex must start with specific number, must contain 2 hyphens and must end with 4 digit numbers

Time:11-03

I am a bit puzzled on how to achieve this after trying so many times. It needs to start with 2 numbers, first number must be 9, then hyphen, then A-Za-z, then dot, then A-Za-z, then hyphen, and end must have 4 digits.

Simple terms for those who don't understand the question: "9<1 digit here>-<sometext.sometext>-<4digits>"

Problem starts with the character dot in the middle of the string. Here is my regex:

^([9])([a-zA-Z0-9]*-*\.){2}[a-zA-Z0-9]\d{4}$

Example input:

  • 90-Amir.h-8394
  • 91-Hamzah.K-4752

Tried figuring out where to put the syntax for the Regex to detect the character dot. But it is not working.

CodePudding user response:

Take a look at this ^9[0-9]-.*\..*-[0-9]{4}$

First, it sets the position at the start of the line with ^
Then it checks if there is a 9 followed by any single number [0-9] and a hyphen -

After that, it checks for random characters until the next hyphen - and makes sure the last part is any random 4 digit number [0-9]{4}

To finish, it's alway good to make sure the end of the line is reached with $

Edit 1:
To make sure the text is formatted like aaaa.bbbb, one can simply use .*\..*
I added this change to the regex above

CodePudding user response:

You can write 9<1 digit here>-<sometext.sometext>-<4digits> as:

^9[0-9]-[A-Za-z] \.[A-Za-z] -[0-9]{4}$

Explanation

  • ^ Start of string
  • 9[0-9] Match 9 and a digit 0-9
  • - Match =
  • [A-Za-z] \.[A-Za-z] Match 1 chars A-Za-z then . and again 1 chars A-Za-z
  • -[0-9]{4} Match - and 4 digits
  • $ End of string

See a regex demo.

  • Related