2

I have a following userName: iphone6s_taylor and iphone6+_taylor.

to find them in text I have created following regular expression:

let regex = "\\B@\(userName)\\b"

But within the following text:

let text = "@iphone6s_taylor @iphone6+_taylor @iphone6+_taylor"

only the first one is found. How to change the regex to find every of them?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

1 Answers1

2

You can use escapedPatternForString:

Returns a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as pattern metacharacters.

Sample usage for your scenario:

let userName = NSRegularExpression.escapedPatternForString("iphone6+_taylor")
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • It works great. Can you simplify your answer to `let userName = NSRegularExpression.escapedPatternForString("iphone6+_taylor")`? Then I will accept this:) – Bartłomiej Semańczyk Jan 07 '16 at 10:15
  • 1
    If you do not like sample solutions in the answer, I will just keep a link here. See [Swift demo](http://swiftstub.com/175585950/) returning `@iphone6+_taylor`. If these links expire, I will just remove the comment. :) – Wiktor Stribiżew Jan 07 '16 at 10:20
  • @stribizhev: There is no problem with sample solutions in the answer, and of course I don't know where you got that method from. But *if* you copied it from another answer then you should add a link to the original, for proper attribution. – Martin R Jan 07 '16 at 10:22
  • Actually, I keep those helper functions locally, and forget to include source links often :( I have a modified version of that function that returns all matches and all submatches for each match, but I guess that is a different story. – Wiktor Stribiżew Jan 07 '16 at 10:27