0

I want to check a certain pattern in a string. My pattern contains 3 parts:

  • Start : First character should be a number or alphabet
  • End : Last character should be a number or alphabet
  • Middle : In between characters can be any combination of numbers, alphabets or a hyphen/minus(-) or @.

I am using following regex:

preg_match('/^[a-zA-Z0-9]+[@\-]*[a-zA-Z0-9]+$/i');

and tested on string :

a-121kabrastreet@90

which evaluates to false. Please rectify my logic. Thank you

1
  • /a-zA-Z/i - it must be ignore-case-twice day. I see three conditions in your "text requirements, and three repetitions in your pattern. Please put "the middle repeated pattern" [@\-]* in words. How is the string "aa" matched, how "aaa"? Commented Mar 4, 2019 at 11:33

1 Answer 1

1

The alphabets and digits should also be added to the character class in the middle. Note that you don't have to escape the hyphen if it is places at the end of the character class.

^[a-zA-Z0-9][@a-zA-Z0-9-]*[a-zA-Z0-9]$
              ^^^^^^^^^

You use the case insensitive flag, your pattern could look like:

/^[a-z0-9][@a-z0-9-]*[a-z0-9]$/i

Regex101 demo | Php demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for quick reply. It works. How can i add backward slash(\) to it. I tried this : /^[a-z0-9]+[a-z0-9@\-\/\\]*[a-z0-9]+$/i and tested with : a-121k/ab/rast@ree-t@9\0, which gives false
There is also a backslash in there, try regex101.com/r/srWvsQ/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.