get all ranges of a substring in a string in swift

后端 未结 5 1386
时光说笑
时光说笑 2020-12-11 20:14

I have a string for example \"ab ad adk fda kla kad ab ab kd\". I want to get all range of ab.(Here ab is present at 3 position so I should get 3 range).In normal scenarion

5条回答
  •  渐次进展
    2020-12-11 20:32

    You are using regular expressions, so you need to take care about characters that have special meaning - . is only one of them.

    If you're doing a search for substrings, I suggest to use the good old rangeOf... methods instead:

    func rangeOfString(_ searchString: String,
               options mask: NSStringCompareOptions,
                 range searchRange: NSRange) -> NSRange
    

    Just keep calling that method on your string (and adjust the searchRange), until no further matches are found.

提交回复
热议问题