You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改正则表达式^(?!.*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-123
    • app-le123
    • a-p-p-l-e-1-2-3
  • Invalid strings (will fail to match):
    • --apple123
    • app--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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:14:56