-9

is there someone that can help me come up with a regex that restricts these characters !@#$%^&*()_-? Most of the post here and google lead me to regex that allow a prescribed set of characters and I cannot seem to have much luck coming up with my own.

Thanks in advance.

EDIT: After some tries came up with below and seems to work so no further help needed:

"Has restricted-characters_?".replace(/^\!|\@|\#|\$|\%|\^|\&|\*|\‌​(|\)|\_|\-|`|\?/, " ")
Morgs
  • 1,076
  • 1
  • 14
  • 26
  • Please post what have you tried so far, and some sample string your regex should match. – Luiso Oct 15 '17 at 17:32
  • 1
    Where is the sample input? what is the expected output? what have you tried to achive that? What error/unexpected result do you get? – L.B Oct 15 '17 at 17:39
  • What does to “to restrict certain characters” mean? And why must you use a regex to do it? – Dour High Arch Oct 15 '17 at 17:51
  • Nevermind all, I've come up with `/^\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\-|\`|\?/.test("Has restricted-characters_?")` and running some tests – Morgs Oct 15 '17 at 17:52
  • 2
    Why is this tagged with two languages? –  Oct 15 '17 at 17:56
  • @Amy The regex will be used both front-end (Javascript) and back-end (C#). – Morgs Oct 15 '17 at 17:59
  • 1
    @Morgs because the regex depends *on the language*. You may not necessarily be able to use the same regex in both places. It is a reasonable question. –  Oct 15 '17 at 18:00
  • Also if anyone is really indeed willing to help. I can't seem to get the _ and ? removed when I `"Has restricted-characters_?".replace(/^\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\-|`|\?/, " ")` the results is `"Has restricted characters_?"` – Morgs Oct 15 '17 at 18:01
  • Ok figured I needed to add the `/g` indicator at the end of the expression... @Amy sorry just got put off with all these questions after asking a question.Thanks all anyway... – Morgs Oct 15 '17 at 18:06
  • 1
    "H@a#s$ re%stri^cted& -characters_?".replace(/[!@#$%^&*()_\-?]/g, "") is this what you're looking for? – Rizan Zaky Oct 15 '17 at 18:12

2 Answers2

2

rgx = (/[\^!@#$%^&*()_?-]/g);
test = str => console.log(str ,str.match(rgx))

test('qwerty')
test('!qwerty')
test('q@werty')
test('qw#erty')
test('qwer$ty')
test('qwert%y')
test('qwerty^')
test('qwertyq&werty')
test('qwertyqwe*rty')
test('qwertyqwert(y')
test('qwertyqwerty)')
test('qwertyqwertyq_wertyqwerty')
test('qwertyqwertyqwe?rtyqwerty')
test('qwertyqwertyqwert-yqwerty')
Guy Yogev
  • 789
  • 4
  • 14
0
[^!@#$%^&*()_?-] 

will do for all the characters. You've got to put them in [ ] with a ^ in front.

Note to escape the - with a \ (Ex: [^!@#$%^&*\-()_?]) or put the - in the very end.

This works, you can try it in here,

https://regexr.com/

Rizan Zaky
  • 3,172
  • 3
  • 18
  • 34