【问题标题】:How to find multiple substrings within braces from a string?如何从字符串中找到大括号内的多个子字符串?
【发布时间】:2018-04-23 09:52:32
【问题描述】:

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

使用这个字符串,我必须在 Swift3 中找到两个子字符串“期望的年收入”和“每笔贷款的收入百分比”。

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

但作为输出,我只得到“期望的年收入”,我怎样才能得到所有子字符串?

【问题讨论】:

  • 你期望的 OP 是什么
  • 输出应该是期望的年收入和每笔贷款的收入百分比。

标签: ios string swift3 substring


【解决方案1】:

试试这个, 希望它会工作

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 %

【讨论】:

  • 它还会在[之前和]之后输出前导和尾随字符
  • @RatulSharker 不会的
【解决方案2】:

这是一个非常好的正则表达式用例 (NSRegularExpression)。正则表达式的原理是在一个字符串中描述一个你想要搜索的“模式”。

在这种情况下,您在两个括号之间进行搜索。

那么代码就是:

    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 中,并且您需要转义反斜杠以获得反斜杠。

(.+?) 有点复杂:括号是“捕获组”,你想得到什么。 . 表示“任意字符”,+ 一次或多次,?+ 之后是贪心运算符,这意味着您希望捕获尽快停止。如果你不说,你的捕获可以在你的情况下“期望的年收入]/([每笔贷款的收入百分比”,这取决于你使用的正则表达式库。基金会似乎默认是贪婪的,据说.

正则表达式并不总是超级简单/直接,但如果您经常进行文本处理,它是一个非常强大的了解工具。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多