[英]Regex including all special characters except space
I have a regex which checks all the special characters except space but that looks weird and too long.我有一个正则表达式,它检查除空格以外的所有特殊字符,但看起来很奇怪而且太长。
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?
Well you could use:那么你可以使用:
[^\w ]
This matches non word characters except for space.这匹配除空格之外的非单词字符。 You may blacklist anything else you also might want by adding it to the above character class.您可以通过将其添加到上述字符 class 来将您可能还需要的任何其他内容列入黑名单。
To match anything that is not a word character nor a whitespace character (cr, lf, ff, space, tab)匹配任何非单词字符或空白字符(cr、lf、ff、空格、制表符)
const specialCharsRegex = new RegExp(/[^\w\s]+|_+/, 'g');
See this demo at regex101 or a JS replace demo at tio.run (used g
flag for all occurrences)请参阅 regex101 上的此演示或 tio.run 上的JS 替换演示(使用g
标志来表示所有事件)
The underscore belongs to word characters [A-Za-z0-9_]
and needs to be matched separately .下划线属于单词字符[A-Za-z0-9_]
,需要单独匹配。
Try this using aA-0-9/az/AZ使用 aA-0-9/az/AZ 试试这个
Pattern regex = Pattern.compile("[^A-Za-z0-9]");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.