Swift 2 NSRegularExpression

时间:2016-01-10 15:35:17

标签: regex swift

最终我希望能够输入一个字符串,如" \ mycard {front1} {back1} \ mycard {front2} {back2} \ mycard {front3} {back3}"并返回每张卡的正面和背面。

我在NSRegularExpression找到了这个网站,但我很难根据我的问题调整它。

这是我到目前为止所拥有的。

import Foundation

func rangeFromNSRange(nsRange: NSRange, forString str: String) -> Range<String.Index>? {
    let fromUTF16 = str.utf16.startIndex.advancedBy(nsRange.location, limit: str.utf16.endIndex)
    let toUTF16 = fromUTF16.advancedBy(nsRange.length, limit: str.utf16.endIndex)

    if let from = String.Index(fromUTF16, within: str), let to = String.Index(toUTF16, within: str) {
        return from ..< to
    }

    return nil
}

do {
    // let input = "My name is Taylor Swift"
    // let regex = try NSRegularExpression(pattern: "My name is (.*)", options: NSRegularExpressionOptions.CaseInsensitive)

    let input = "mycard{front}{back}"
    let regex = try NSRegularExpression(pattern: "mycard{(.*)}{(.*)}", options: NSRegularExpressionOptions.CaseInsensitive)

    let matches = regex.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count))

    if let match = matches.first {
        let range = match.rangeAtIndex(1)
        if let swiftRange = rangeFromNSRange(range, forString: input) {
            let name = input.substringWithRange(swiftRange)
        }
    }
} catch {
    // regex was bad!
}

2 个答案:

答案 0 :(得分:3)

如我的评论中所述,您需要转义 myImageView.image = image self.dismissViewControllerAnimated(true, completion: nil) {。这导致以下正则表达式:}

然后,您可能希望稍微更改匹配逻辑以输出预期结果:

mycard\\{(.*)\\}\\{(.*)\\}

哪个输出

  


  回

如果要匹配多张卡,请使用以下正则表达式:

if let match = matches.first {
    for i in 1..<match.numberOfRanges {
        let range = match.rangeAtIndex(i)
        if let swiftRange = rangeFromNSRange(range, forString: input) {
            let name = input.substringWithRange(swiftRange)
            print(name)
        }
    }
}

然后迭代匹配

mycard\\{([^{]*)\\}\\{([^{]*)\\}

对于输入for match in matches { for i in 1..<match.numberOfRanges { let range = match.rangeAtIndex(i) if let swiftRange = rangeFromNSRange(range, forString: input) { let name = input.substringWithRange(swiftRange) print(name) } } } ,输出正确

  


  回到
  FRONT1
  back1

答案 1 :(得分:0)

我放弃了正则表达式。我只是觉得它不会在这里发挥作用。我提出了另一个解决方案。

import Foundation

extension String {
    subscript (r: Int) -> Character? {
        var cur = 0
        for char in self.characters {
            if cur == r {
                return char
            }
            cur += 1
        }
        return nil
    }

    subscript (r: Range<Int>) -> String {
        return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
    }

    func parseBrackets () -> [String]? {
        var list: [String] = []
        var level = 0
        var start = 0
        for var i=0; i < self.characters.count - 1; i++ {
            if self[i] == "{" {
                level += 1
                if level == 1 {
                    start = i + 1
                }
            } else if self[i] == "}" {
                if level == 1 {
                    list.append(self[start..<i])
                }
                level -= 1
            }
        }

        if list.count > 0 {
            return list
        } else {
            return nil
        }
    }
}



let testString = "mycard{f{}ront}{termins{x}{n}} mycard{front1}{back1} mycard{front2}{back2}"
let list = testString.parseBrackets()

for a in list! {
    print(a)
}

提供所需的输出

f{}ront
termins{x}{n}
front1
back1
front2