JavaScript如何修改正则表达式以排除指定特殊字符?
Alright, let's tweak your regex to fit your requirements perfectly!
Your original /^\S.*$/ works well for matching strings starting with non-whitespace and covering global character sets, but it allows all sorts of unwanted special characters. To restrict it to only keep multi-language letters (Chinese, Arabic, Cyrillic, etc.), digits, and your specified symbols ,, ., ', -, we can leverage Unicode property classes to cleanly cover all those global characters.
Here's the updated regex:
/^[\p{L}\p{N},.'-]+$/
Let me break down each component so you understand exactly what's happening:
^and$: These anchors make sure we check the entire string, not just a part of it. No more partial matches slipping through!- The character set
[\p{L}\p{N},.'-]defines all allowed characters:\p{L}: Matches any Unicode letter from any language—this is key for supporting Chinese, Arabic, Cyrillic, and every other alphabet out there.\p{N}: Matches any Unicode digit (so not just 0-9, but also numerals from other scripts like Devanagari or Arabic-Indic).,.'-: The four special characters you want to retain. We place-at the end of the set to avoid it being treated as a range operator (no need to escape it here).
+: Ensures the string has at least one allowed character, which keeps the behavior consistent with your original regex (no empty strings, no strings starting with whitespace).
Quick validation examples:
- ✅ Matches:
مرحبا, 你好-world'123(mix of Arabic, Chinese, allowed symbols, and digits) - ❌ Rejects:
Hello!@#Test(contains disallowed special characters!@#) - ❌ Rejects:
CyrillicText(starts with whitespace) - ❌ Rejects:
Hello World(contains whitespace—if you need to allow spaces, just add\sto the character set:/^[\p{L}\p{N},.'-\s]+$/)
内容的提问来源于stack exchange,提问作者Bargain23
相关产品推荐
相关产品推荐

