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
: Match123
: Not match1-2-3
: Not match1-a
: Match
3
Answers
You can try
^(?=.*[a-zA-Z])[w-]+$
You can attempt to match the regular expression
Demo
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.
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 stringSee a regex demo.