Swift extract regex matches

前端 未结 11 1936
无人及你
无人及你 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:24

    This is how I did it, I hope it brings a new perspective how this works on Swift.

    In this example below I will get the any string between []

    var sample = "this is an [hello] amazing [world]"
    
    var regex = NSRegularExpression(pattern: "\\[.+?\\]"
    , options: NSRegularExpressionOptions.CaseInsensitive 
    , error: nil)
    
    var matches = regex?.matchesInString(sample, options: nil
    , range: NSMakeRange(0, countElements(sample))) as Array
    
    for match in matches {
       let r = (sample as NSString).substringWithRange(match.range)//cast to NSString is required to match range format.
        println("found= \(r)")
    }
    

提交回复
热议问题