0

I have this String:

let string = "Users: [Ricky], [Bob], [Jane]"

and I'm trying to make a string Array (Ex. ["Ricky","Bob","Jane"]) with words that are wrapped by brackets.

Question: How do I substring and iterate results?

Is Regex the way to go?

let string = "Users: [Ricky], [Bob], [Jane]"
let pattern = "/[(.*?)]/"
let regex = try! NSRegularExpression(pattern: pattern)
let result = regex.matches(in:string, range:NSMakeRange(0, string.utf8.count))
Ricky
  • 100
  • 1
  • 1
  • 7
  • 1
    Try `let pattern = "(?<=\\[).*?(?=\\])"` – Wiktor Stribiżew May 28 '18 at 19:15
  • Try `let pattern = "\[(.*?)\]"`. Also `NSRange` counts in UTF-16 code units so `NSMakeRange(0, string.utf16.count)` – Code Different May 28 '18 at 19:23
  • 1
    Use my regex with code from [here](https://stackoverflow.com/questions/27880650/swift-extract-regex-matches). – Wiktor Stribiżew May 28 '18 at 19:30
  • It should be noted that the duplicate only has two (low vote) answers that are applicable to this question and none of them help the OP of this question determine what the proper regular expression needs to be. – rmaddy May 28 '18 at 20:05
  • @rmaddy, MartinR's answer provides everything needed except the pattern. I reopened it because your pattern does work, as does all of your code. – vacawama May 28 '18 at 20:13
  • @vacawama Martin's answer doesn't work in this case because it doesn't handle the capture group which is needed to avoid returning the `[ ]` from the results. His answer is great if you don't need capture groups. – rmaddy May 28 '18 at 20:16
  • @rmaddy, I used Wiktor's pattern with MartinR's code and it did the right thing. – vacawama May 28 '18 at 20:21
  • @vacawama Indeed it does. It seems that RE gives just the part between the `[ ]`. Good to know. I'm not as familiar with the `?<=` and `?=` syntax. I need to study that. – rmaddy May 28 '18 at 20:27
  • @rmaddy, those are [lookahead and lookbehind assertions](https://www.regular-expressions.info/lookaround.html). – vacawama May 28 '18 at 20:38

1 Answers1

2

The following pattern is what you need:

let pattern = "\\[([^]]*)\\]"

\\[ - a literal [

[^]]* - Any number of characters other than a ]

\\] - a literal ]

The ( ) are only needed if you need to reference the text inside the square brackets.

Here is complete working code:

let string = "Users: [Ricky], [Bob], [Jane]"
let pattern = "\\[([^]]*)\\]"
let regex = try! NSRegularExpression(pattern: pattern)
let result = regex.matches(in:string, range:NSMakeRange(0, string.utf8.count))
let names = result.map { (string as NSString).substring(with: $0.range(at: 1)) }
print(names)

Output:

["Ricky", "Bob", "Jane"]

rmaddy
  • 314,917
  • 42
  • 532
  • 579