1

I wanted to validate the Name data files with following condition

  • the Name contains digits 0 to 9, not all numeric
  • Name can contain hyphen -, provided that it is not the first or last character of the name
  • Name must contain 2 character, rest char are optional

So I tried the following Regex

    const regExp = /^[a-zA-Z0-9]+[a-zA-Z_-]+[a-zA-Z0-9]$/;

I need at least two characters, remaining are optional in the regExp everything works fine except this [a-zA-Z0-9] in the last, I want to make this optional

7
  • 2
    You need this: /^[a-zA-Z0-9][a-zA-Z_-]*[a-zA-Z0-9]$/ Commented Sep 5, 2019 at 15:20
  • The "can't all be numeric" stipulation makes this a difficult regex. Commented Sep 5, 2019 at 15:30
  • 2
    /^(?=.{2})(?!\d+$)[a-zA-Z0-9]+(?:[_-][a-zA-Z0-9]+)*$/ Commented Sep 5, 2019 at 15:30
  • Is 2-2 a valid name? If yes, then @WiktorStribiżew has the solution. Commented Sep 5, 2019 at 15:32
  • 2
    Then a better one is requiring a letter - /^(?=.{2})(?![^a-zA-Z]+$)[a-zA-Z0-9]+(?:[_-][a-zA-Z0-9]+)*$/ Commented Sep 5, 2019 at 15:38

1 Answer 1

1

You may consider using

/^(?=.{2})(?![^a-zA-Z]+$)[a-zA-Z0-9]+(?:[_-][a-zA-Z0-9]+)*$/

See the regex demo

Details

  • ^ - start of string
  • (?=.{2}) - at least two chars
  • (?![^a-zA-Z]+$) - the string can't have no ASCII letter
  • [a-zA-Z0-9]+ - 1+ ASCII alnum chars
  • (?:[_-][a-zA-Z0-9]+)* - 0 or more sequences of _ or - followed with 1+ ASCII alnum chars
  • $ - 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.