简体   繁体   English

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

[英]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.

相关问题 我想要一个正则表达式,它将 select 所有字符,包括特殊字符,除了最后 4 个字符。 香草JS - I want a regex that will select all characters including special characters, except the Last 4 Characters. Vanilla JS 正则表达式删除除数字以外的所有特殊字符? - Regex remove all special characters except numbers? 正则表达式仅包含数字和2个特殊字符(仅带空格) - Regex for including only numbers and 2 special characters with space only 使用 JavaScript 从字符串中删除除空格外的所有特殊字符 - Remove all special characters except space from a string using JavaScript 正则表达式:允许除四个之外的所有字符,限制包括下划线 - Regex: Allow all characters except four, restriction including underscore 正则表达式接受除数字和特殊字符外的所有字符(空格,带重音符号) - Regex acepting all chars(spaces, accentuated) except numbers and special characters Javascript regex - 删除除分号以外的所有特殊字符 - Javascript regex - remove all special characters except semi colon Javascript regEx 删除除特殊字符之间的所有括号 - Javascript regEx to remove all parentheses except between special characters 用于忽略除空格和连字符以外的所有特殊字符的 JS 正则表达式 - JS Regex for ignoring all special characters but space and hyphen Javascript:正则表达式捕获空格和特殊字符除了单词内的连字符 - Javascript: Regex to capture white space and special characters EXCEPT hyphens within words
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM