Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx match x if foo or bar exists, but not if only bar exists

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
like image 571
Wubzy Avatar asked Feb 03 '26 21:02

Wubzy


1 Answers

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