-1

I am trying to construct Regex but it doesn't work. Can anyone help?

I have a string, which I want to remove the following characters:

*_-+=#:><&[]\n

And instruct also to remove all text between (/ and )

Code is belkow:

if let regex = try? NSRegularExpression(pattern: "&[^*_-=;](\\)*;", options: .CaseInsensitive) {
let modString = regex.stringByReplacingMatchesInString(testString, options: .WithTransparentBounds, range: NSMakeRange(0, testString.characters.count), withTemplate: "")
print(modString)

}

Tal Zion
  • 6,308
  • 3
  • 50
  • 73
  • 1
    By testing your regex in https://regex101.com, it failed because of the "-" character. Are you sure about your regex construction? – Larme Feb 01 '16 at 16:36
  • @Larme No! That is why I came for help in Stack :).. There is something wrong in my regex. This is what I need to replace by whitespace *_-+=#:><&[] – Tal Zion Feb 01 '16 at 16:38
  • Use Do-Try-Catch with an error variable instead of `try?` and a nice error message will appear explaining that the regex is invalid. Lesson of the day: do not ignore error messages. :) – Eric Aya Feb 01 '16 at 16:39
  • 1
    Ok. It just that it wasn't clear since you mentioned that it didn't work on Swift 2.0. Indeed, with your question title, it seemed to be related to Swift. – Larme Feb 01 '16 at 16:39
  • @Larme Thanks. I've edited my Q – Tal Zion Feb 01 '16 at 16:44

1 Answers1

2

You can use

"\\(/[^)]*\\)|[*\r\n_+=#:><&\\[\\]-]"

See the regex demo

The \\(/[^)]*\\) alternative deals with all text between (/ and ) and [*_+=#:><&\\[\\]-] will match all the single characters you need to match.

Note that the hyphen in your regex must either be double-escaped, or placed at the start or end of the character class. Your regex did not work because it created an invalid range:

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563