2

How shall we write a regular expression to validate a string that should have a length of a minimum of 1 character and a maximum of 50 characters, have both upper case and lower case, alphanumeric, include space, and have mostly used special characters like @,._-&$#? The first character should be either alphabet or number then the rest can be as mentioned above.

*If it is only one character then it should be an alphanumeric one

I have tried a regex with my limited knowledge which looks like

^[a-zA-z]*[a-zA-Z\d\-_@&$%#\s]{1,50}$

But I am not able to match the string if there is only one character given, can anyone guide me to fix this

13
  • Can include one space or more? Commented Oct 27, 2020 at 7:19
  • Can Include 1 or more spaces but the begining of the text should be an alphabet @alextrastero Commented Oct 27, 2020 at 12:44
  • Thanks for the reference, I will check that as well @WiktorStribiżew Commented Oct 27, 2020 at 12:45
  • 1
    @WiktorStribiżew I have tried to create a regex with my limited knowledge and your reference and i have edited the question with that. can you help me fix this Commented Oct 27, 2020 at 15:25
  • 1
    Aha, so you want to use a Unicode-aware \w? See this answer, and you will need to use /^(?=\p{Alphabetic})[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}@,.&$%#\s-]{1,50}$/u Commented Oct 27, 2020 at 15:43

1 Answer 1

2

You can use

/^(?=[\p{L}0-9])[\p{L}\p{N}_@,.&$%#\s-]{1,50}$/u

See the regex demo

Details

  • ^ - start of string
  • (?=[\p{L}0-9]) - the first char must be a Unicode letter (\p{L}) or an ASCII digit
  • [\p{L}\p{N}_@,.&$%#\s-]{1,50} - one to fifty
    • \p{L} - any Unicode letter
    • \p{N} - any Unicode digit
    • _@,.&$%#- - any of these chars
    • \s - any whitespace
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

Comments

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.