簡體   English   中英

正則表達式包括除空格外的所有特殊字符

[英]Regex including all special characters except space

我有一個正則表達式,它檢查除空格以外的所有特殊字符,但看起來很奇怪而且太長。

const specialCharsRegex = new RegExp(/@|#|\$|!|%|&|\^|\*|-|\+|_|=|{|}|\[|\]|\(|\)|~|`|\.|\?|\<|\>|,|\/|:|;|"|'|\\/).

This looks too long and if i use regex (\W) it also includes the space.
Is there is any way i can achieve this?

那么你可以使用:

[^\w ]

這匹配除空格之外的非單詞字符。 您可以通過將其添加到上述字符 class 來將您可能還需要的任何其他內容列入黑名單。

匹配任何單詞字符空白字符(cr、lf、ff、空格、制表符)

const specialCharsRegex = new RegExp(/[^\w\s]+|_+/, 'g');

請參閱 regex101 上的此演示或 tio.run 上JS 替換演示(使用g標志來表示所有事件)

下划線屬於單詞字符[A-Za-z0-9_] ,需要單獨匹配。

使用 aA-0-9/az/AZ 試試這個

Pattern regex = Pattern.compile("[^A-Za-z0-9]");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM