Swift extract regex matches

前端 未结 11 2172
无人及你
无人及你 2020-11-21 23:44

I want to extract substrings from a string that match a regex pattern.

So I\'m looking for something like this:

func matchesForRegexInText(regex: St         


        
11条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 00:20

    @p4bloch if you want to capture results from a series of capture parentheses, then you need to use the rangeAtIndex(index) method of NSTextCheckingResult, instead of range. Here's @MartinR 's method for Swift2 from above, adapted for capture parentheses. In the array that is returned, the first result [0] is the entire capture, and then individual capture groups begin from [1]. I commented out the map operation (so it's easier to see what I changed) and replaced it with nested loops.

    func matches(for regex: String!, in text: String!) -> [String] {
    
        do {
            let regex = try NSRegularExpression(pattern: regex, options: [])
            let nsString = text as NSString
            let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length))
            var match = [String]()
            for result in results {
                for i in 0..

    An example use case might be, say you want to split a string of title year eg "Finding Dory 2016" you could do this:

    print ( matches(for: "^(.+)\\s(\\d{4})" , in: "Finding Dory 2016"))
    // ["Finding Dory 2016", "Finding Dory", "2016"]
    

提交回复
热议问题