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

技术问询:如何编写验证字符串必须包含特殊字符的正则表达式?

Regex to Validate Strings Containing At Least One Special Character

Hey there, let's work through this regex problem together. You need to ensure a given string includes at least one special character—here are a couple of practical approaches depending on how you define "special characters."

Basic Check for Any Non-Alphanumeric/Non-Whitespace Character

If you’re going with the common definition (any character that isn’t a letter, digit, or space), this regex will get the job done:

^.*[^\w\s].*$

Let me break down what each piece does so you understand it fully:

  • ^ Anchors the match to the start of the string
  • .* Matches any number (including zero) of characters before the special character
  • [^\w\s] The core part: it targets any character that isn’t a word character (letters, digits, underscores—covered by \w) or whitespace (spaces, tabs, newlines—covered by \s)
  • .* Matches any characters that come after the special character
  • $ Anchors the match to the end of the string

Custom Special Character List

If you only want to enforce a specific set of special characters (like !@#$%^&* instead of all non-alphanumerics), use a positive character set instead. For example:

^.*[!@#$%^&*].*$

Just swap out the characters inside [] with exactly the special characters you need to require.

Quick Tips to Avoid Common Mistakes

  • If your special character list includes ], put it at the start of the character set (like []!@#]) so the regex doesn’t interpret it as closing the set early.
  • For -, either place it at the very start/end of the set (e.g., [-!@#]) or escape it with a backslash ([\-!@#]) to stop it from being treated as a range indicator.
  • If you don’t want to allow whitespace at all, simply remove \s from the first regex, making it ^.*[^\w].*$

内容的提问来源于stack exchange,提问作者klöppi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:01:07