Home > Mobile >  Regex including all special characters except space
Regex including all special characters except space

Time:10-09

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?

CodePudding user response:

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.

CodePudding user response:

To match anything that is not a word character nor a whitespace character (cr, lf, ff, space, tab)

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)

The underscore belongs to word characters [A-Za-z0-9_] and needs to be matched separately.

CodePudding user response:

Try this using a-A-0-9/a-z/A-Z

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

  • Related