如何修复正则表达式:移除下划线与&,仅允许指定合法字符
Fixing Your Regex to Match Only Allowed Characters
Let's break down what's wrong with your current regex and fix it properly:
Issues with the Original Regex: ^[\.\w?\-' ]+$
\wincludes underscores: The shorthand\wmatchesa-zA-Z0-9_—the underscore is the unwanted character here that's slipping through.- HTML entity confusion:
'is an HTML-escaped way to write a single quote, but in a regex pattern, this gets interpreted as literal characters:&,a,m,p,;,a,p,o,s,;. That's why&is being incorrectly allowed.
The Corrected Regex
Use this pattern instead, which explicitly defines only the characters you want to allow:
^[a-zA-Z0-9' ?-.]+$
Breakdown of the Fixed Regex:
a-zA-Z0-9: Matches all uppercase/lowercase letters and digits (no underscores, since we're avoiding\w).': Directly includes the single quote (no need for HTML entities here—just write the literal character, making sure your string escaping handles it correctly if needed).: Allows spaces.?: Allows question marks (no escaping needed inside the character set).-: Placed at the end of the character set to avoid being interpreted as a range operator (likea-z). If you put it elsewhere, you'd need to escape it with\-, but putting it last is cleaner..: Matches literal periods (no escaping needed inside the character set).+: Ensures there's at least one allowed character (adjust to*if empty strings should be allowed).^and$: Anchor the regex to match the entire string, not just a substring.
Testing Examples
- ✅ Should match:
Hello World? This is a test-123. 'Valid string' - ❌ Should NOT match:
Hello_World(contains underscore),Hello&World(contains &),Invalid!(contains exclamation mark)
内容的提问来源于stack exchange,提问作者ShaQ.Blogs
相关产品推荐
相关产品推荐

