Swift Regex Matching

后端 未结 1 369
轻奢々
轻奢々 2021-01-27 16:36

The pattern is not the issue

I have a regex string

var elementRegex = \"([A-Z][a-z]?)(\\\\d*)?\"

I want to match t

相关标签:
1条回答
  • 2021-01-27 17:26

    This is not a Swift specific question but more a Cocoa question. You don't specify wether you are developing for OS X or iOS but both have excellent regular expression support via NSRegularExpression and NSString.

    Here is and example of their usage in Swift:

    let s: NSString = "Al3Br3"
    if let r = NSRegularExpression(pattern: "([A-Z][a-z]?)(\\d*)?", options: NSRegularExpressionOptions.allZeros, error: nil) {
        for match in r.matchesInString(s, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, s.length)) as [NSTextCheckingResult] {
            println("Match:")
            for i in 0..<match.numberOfRanges {
                println("\(i): \(s.substringWithRange(match.rangeAtIndex(i)))")
            }
        }
    }
    

    This results in:

    Match:
    0: Al3
    1: Al
    2: 3
    Match:
    0: Br3
    1: Br
    2: 3
    
    0 讨论(0)
提交回复
热议问题