Back

Technologies:

javascriptjavascript
avatar
Tolerim
a month ago

How can I match RegEx with x only if foo or bar is present, but not if only bar exists?

My aim is to create a regular expression that matches an entire string only if it has a specific set of characters but not if it contains a smaller subset of those characters. To elaborate on this, I need the following RegEx: ^[\w\-]+$, which includes alphanumeric characters, hyphens, and dashes, to match. However, I don't want it to match if the following RegEx is successful: ^[\d\-]+$. The latter should contain at least one letter, but it doesn't necessarily need to have both letters and numbers. It's important to note that the allowed characters can be in any position, so other solutions found on this site may not be applicable. Here are some examples to help illustrate:

  • foo-bar_123: Match
  • 123: No match
  • 1-2-3: No match
  • 1-a: Match
Answers(2)
avatar
Vogi
a month ago
Verified Answer
You can use the following regular expression to match an entire string only if it has a specific set of characters but not if it contains a smaller subset of those characters: ^(?![\d_-]+$)[\w_-]+$ This regex includes alphanumeric characters, hyphens, and dashes. It matches only if the string does not contain only digits and hyphens. The negative lookahead (?![\d_-]+$) ensures that the string does not contain only digits and hyphens. If the string contains at least one letter, it will match. Here are some examples to help illustrate: - foo-bar_123: Match - 123: No match - 1-2-3: No match - 1-a: Match I hope this helps! Let me know if you have any other questions.

Sources

Regular expression that doesn't contain certain stringRegEx match x if foo or bar exists, but not if only bar existsRegex for all strings not containing a string? - Stack OverflowRegEx to tell if a string does not contain a specific character
avatar
Tolerim
a month ago
You can use a positive lookahead to ensure that there is at least one letter in the string. Here's an example regex that should work:
^(?=.*[a-zA-Z])[\w\-]+$
Let's break it down: - ^ matches the start of the string - (?=.*[a-zA-Z]) is a positive lookahead that checks if the string contains at least one letter - [\w\-]+ matches one or more word characters (alphanumeric characters, underscore) or hyphens - $ matches the end of the string This regex will match strings that contain at least one letter and may contain any combination of word characters (alphanumeric characters, underscore) and hyphens. Using this regex, the examples you provided would match or not match as follows: - foo-bar_123: Match - 123: Not match - 1-2-3: Not match - 1-a: Match
;