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

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 \s to the character set: /^[\p{L}\p{N},.'-\s]+$/)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:24:10