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

关于正则表达式匹配非字母数字空格连字符无效字符的技术咨询

Regex to Match Strings with Invalid Characters (Excluding Letters, Numbers, Spaces, and Hyphens)

Got it, let's break down how to build this regex exactly as you need it.

The Regex Pattern

To detect any string that contains at least one character outside your allowed set, use this core pattern:

[^A-Za-z0-9\s-]

If you need to match the entire invalid string (for validation workflows where you want to flag the full entry), wrap it with wildcards to cover the whole string:

.*[^A-Za-z0-9\s-].*

What Each Part Means

Let's unpack the negated character class that makes this work:

  • [^...]: This is a negated character class—it matches any character that is NOT listed inside the brackets.
  • A-Za-z: Covers all uppercase and lowercase English letters.
  • 0-9: Matches all digits from 0 to 9.
  • \s: Matches any whitespace character (regular spaces, tabs, newlines, etc.). If you only want to allow regular spaces (not tabs/newlines), replace \s with a literal space .
  • -: Placed at the end of the character class so it's interpreted as a literal hyphen (instead of defining a range like A-Z). You could also escape it as \- if you prefer, but putting it at the end is cleaner.

Quick Examples

  • Valid strings (won't trigger a match):
    • "My String-123"
    • "hello-world 456"
    • "TEST 789"
  • Invalid strings (will trigger a match):
    • "Hello!World" (contains !)
    • "Test@123" (contains @)
    • "Invalid_String" (contains _)

Quick Notes

  • This works across most common regex engines (JavaScript, Python, Java, etc.). Just confirm your engine treats \s consistently (most do, but swap for a literal space if you need strict space-only matching).
  • For validation use cases, the simple [^A-Za-z0-9\s-] is sufficient—if it finds a match, the string has invalid characters.

内容的提问来源于stack exchange,提问作者Saad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:02:52