skip to Main Content

I’m trying to write an expression that can match a whole string if it has a set of characters, but only if it contains a smaller subset of those characters.

To include my specific use case, I’d like this RegEx: ^[w_-]+$ (being that there can be alphanumeric characters, hyphens, and dashes), to match, but not to match if this RegEx is a match: ^[d_-]+$ (being that there must be at least one letter in the string, but it does not have to contain both letters and numbers).

Any of the allowed characters may be at any position, which makes the other relevant questions on this site not apply in my case.

  • foo-bar_123: Match
  • 123: Not match
  • 1-2-3: Not match
  • 1-a: Match

3

Answers


  1. You can try ^(?=.*[a-zA-Z])[w-]+$

    Login or Signup to reply.
  2. You can attempt to match the regular expression

    ^[w-]*[a-zA-Z][w-]*$
    

    Demo

    Login or Signup to reply.
  3. Another option could be first matching the allowed characters without a character a-zA-Z

    Then match at least a single a-zA-Z followed by all the allowed characters for the full match.

    ^[0-9_-]*[a-zA-Z][w-]*$
    

    Explanation

    • ^ Start of string
    • [0-9_-]* Match 0+ times a digit 0-9 or _ or -
    • [a-zA-Z] Match a single char a-zA-Z
    • [w-]* Match optional word chars or -
    • $ End of string

    See a regex demo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search