rohit garg
rohit garg

Reputation: 323

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?

Upvotes: 1

Views: 931

Answers (3)

Radoslav Atanasov
Radoslav Atanasov

Reputation: 1

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

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

Upvotes: 0

bobble bubble
bobble bubble

Reputation: 18490

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.

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

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.

Upvotes: 2

Related Questions