0

I have a string [Desired Annual Income] /([Income per loan %] /100)

Using this string, I have to find two sub strings 'Desired Annual Income' and 'Income per loan %' in Swift3.

I am using below code to achieve this 'How do I get the substring between braces?':

  let myString = "[Desired Annual Income]  /([Income per loan %] /100)"
  let start: NSRange = (myString as NSString).range(of: "[")
  let end: NSRange = (myString as NSString).range(of: "]")
   if start.location != NSNotFound && end.location != NSNotFound && end.location > start.location {
      let result: String = (myString as NSString).substring(with: NSRange(location: start.location + 1, length: end.location - (start.location + 1)))          
      print(result)
   }

But as an output I am getting only 'Desired Annual Income', How can I get all substrings?

Muthusamy
  • 306
  • 1
  • 11
Anand Gautam
  • 2,541
  • 3
  • 34
  • 70

2 Answers2

0

Try this, Hope it will work

let str = "[Desired Annual Income]  /([Income per loan %] /100)"
let trimmedString = str.components(separatedBy: "]")
for i in 0..<trimmedString.count - 1{ // not considering last component since it's of no use hence count-1 times loop
    print(trimmedString[i].components(separatedBy: "[").last ?? "")
}

Output:-

Desired Annual Income
Income per loan %
Aditya Srivastava
  • 2,630
  • 2
  • 13
  • 23
0

It's a very good use case for regular expressions (NSRegularExpression). The principle of regular expressions is to describe a "pattern" that you want to search in a string.

In that case you search something between two brackets.

The code is then:

    let str = "[Desired Annual Income]  /([Income per loan %] /100)"

    if let regex = try? NSRegularExpression(pattern: "\\[(.+?)\\]", options: [.caseInsensitive]) {
        var collectMatches: [String] = []
        for match in regex.matches(in: str, options: [], range: NSRange(location: 0, length: (str as NSString).length)) {
            // range at index 0: full match (including brackets)
            // range at index 1: first capture group
            let substring = (str as NSString).substring(with: match.range(at: 1))
            collectMatches.append(substring)
        }
        print(collectMatches)
    }

For the explanation about regular expressions, there are plenty of tutorial on internet. But in very short:

\\[ and \\]: opening and closing brackets characters (the double backslashes are because brackets have a meaning in regular expression, so you need to escape them. In a text editor one backslash is enough, but you need a second one because you are in a String and you need to escape the backslash to have a backslash.

(.+?) is a bit more complex: the parentheses are the "capture group", what you want to get. . means "any character", + one or more time, ? after a + is the greedy operator, which means that you want the capture to stop ASAP. If you don't put it, your capture can be in your case "Desired Annual Income] /([Income per loan %", depending of the regex library that you are using. Foundation seems to be greedy by default, that being said.

Regex are not always super easy/direct, but if you do often text processing, it's a very powerful tool to know.

Renaud
  • 380
  • 4
  • 13