0

I have a string "this [is] not req!red"

i am trying to create a regex which will pick "characters" not specified in the list

[-a-zA-Z.,-()=\s\+:?!*\;><0-9]

any suggestions how to achieve this?

Language is C#

Usman Masood
  • 1,847
  • 2
  • 17
  • 33
  • Have you googled "regex not"? It's that simple. `[abc]` is "the character a, b or c". `[^abc]` is "any character that isn't a, b or c". `[^abc]+` is "any character that isn't a, b or c matched 1 to infinity times". – h2ooooooo Apr 25 '14 at 13:18
  • depends on your language, `^` at the beginning generally negates a character class and you can use captures to get them: `([^-a-zA-Z.,-()=\s+:?!*\;><0-9]). – perreal Apr 25 '14 at 13:20
  • What is your expected output? – anubhava Apr 25 '14 at 13:29
  • okay your regex changed to `[^-a-zA-Z.,\-()=\s\+:?!*\;><0-9]` selects only the square brackets so what is your problem? – aelor Apr 25 '14 at 13:29
  • Is your goal to end up with `this is not reqred`? To filter out all unwanted characters? Every letter is *unwanted*? – aliteralmind Apr 25 '14 at 13:32
  • Which programming language are you using ? – Pedro Lobito Apr 25 '14 at 13:38
  • I am using C#, basically i want to replace all characters which don't match this particular pattern. – Usman Masood Apr 25 '14 at 14:10

2 Answers2

2

Your regex is a positive character class that matches each legal character specified in it:

[-a-zA-Z.,\-()=\s+:?!*\;><0-9]

Regular expression visualization

Debuggex Demo

The characters you don't want aren't matched. To switch this around, to match only the characters you want, make it a negative character class, by adding the ^ as its first character:

[^-a-zA-Z.,\-()=\s+:?!*\;><0-9]

Regular expression visualization

Debuggex Demo

To capture the matches, put the entire regex into a capturing group:

([-a-zA-Z.,\-()=\s+:?!*\;><0-9])

or

([^-a-zA-Z.,\-()=\s+:?!*\;><0-9])

Then iterate through the matches in your language of choice. Each character is in capture group one.

I'm uncertain of your goal. More information would help us give you better answers.


Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference.

Community
  • 1
  • 1
aliteralmind
  • 18,274
  • 16
  • 66
  • 102
1

I think you need this :

[^-a-zA-Z.,\-()=\s\+:?!*\;><0-9]

the ^ will negate every character present in the list .

demo here : http://regex101.com/r/vX0oQ7

so basically in your example, it will not select anything apart from the square brackets .

this [is] not req!red
     |  |
aelor
  • 9,803
  • 2
  • 27
  • 43