如何从字符串中的大括号内查找多个子字符串?

How to find multiple substrings within braces from a string?

我有一个字符串[Desired Annual Income] /([Income per loan %] /100)

使用这个字符串,我必须在 Swift3 中找到两个子字符串 'Desired Annual Income' 和 'Income per loan %'。

我正在使用下面的代码来实现这个'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)
   }

但作为输出,我只得到 'Desired Annual Income',我怎样才能得到所有的子字符串?

试试这个, 希望有用

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 ?? "")
}

输出:-

Desired Annual Income
Income per loan %

这是一个非常好的正则表达式用例 (NSRegularExpression)。正则表达式的原理是在一个字符串中描述一个你要查找的"pattern"。

在那种情况下,您可以搜索两个括号之间的内容。

那么代码是:

    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)
    }

关于正则表达式的解释,网上有很多教程。但简而言之:

\[\]:左括号和右括号字符(双反斜杠是因为括号在正则表达式中有含义,所以你需要转义它们。在文本编辑器中,一个反斜杠是够了,但是你需要第二个,因为你在 String 中,你需要转义反斜杠以获得反斜杠。

(.+?) 有点复杂:括号是 "capture group",你想要得到的。 .表示"any character"、+一次或多次,+后的?是贪婪运算符,表示希望尽快停止捕获。如果你不放它,你的捕获可以是你的情况 "Desired Annual Income] /([Income per loan %",这取决于你使用的正则表达式库。话虽如此,基金会似乎默认是贪婪的。

正则表达式并不总是超级easy/direct,但如果你经常进行文本处理,它是一个非常强大的工具。