如何修改正则表达式^(?!.*bar).*$以验证字符串不含连续双杠
Got it, let's tackle this regex problem!
First, let's recap how the original regex you referenced works: ^(?!.*bar).*$ uses a negative lookahead ((?!...)) to assert that the string doesn't contain the substring bar anywhere. To adapt this to your needs—blocking strings with consecutive --—we just need to tweak the lookahead target, plus add constraints for your allowed characters (letters, numbers, and single hyphens).
The Solution
Here's the regex you need:
^(?!.*--)[a-zA-Z0-9-]+$
Breakdown of Each Part
Let's break this down so you understand exactly what's happening:
^: Anchors the match to the start of the string (ensures we check the whole string, not just a part of it)(?!.*--): The negative lookahead that does the heavy lifting. It asserts that nowhere in the string will we find the consecutive hyphens--. The.*means "any characters (zero or more)" before the--, so it checks every position in the string.[a-zA-Z0-9-]+: Matches one or more of your allowed characters: uppercase/lowercase letters, digits, or single hyphens. The+ensures the string isn't empty.$: Anchors the match to the end of the string (again, ensures we're validating the entire string)
Testing Against Your Examples
Let's verify this works with your test cases:
- Valid strings (will match successfully):
apple123-apple-123app-le123a-p-p-l-e-1-2-3
- Invalid strings (will fail to match):
--apple123app--le123
Bonus: Even More Strict (If Needed)
If you ever wanted to add extra rules (like disallowing leading/trailing hyphens), you could adjust the regex to:
^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$
This version ensures hyphens are only between alphanumeric characters, no leading/trailing ones—but since your valid examples include -apple-123, this isn't necessary for your current use case.
Hope that clears things up! 😊
内容的提问来源于stack exchange,提问作者Sandun Perera

