Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

ios - RegEx in Swift?

I am learning Swift, and I have (another) question. Are there regular espressions in Swift, and, if so, how do I use them?

In my research, I found some conflicting information. Apple Developer documents has something mentioning RegEx, but it looks so different than any other language i've seen. If this is the solution, how do I use it?

This website, on the other hand, suggests that RegEx doesn't exist in Swift. Is this correct?

In case it helps, I am trying to use regex to get the average price of a bitcoin from JSON-style API that contains the price, but also a lot of stuff I don't want.

Sorry for another basic question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, Swift is lacking regex literals. But the external link you are referring to exposes 2 ways to use regex.

  1. Make a class wrapper around NSRegularExpression and use this class.
  2. Calling the Foundation method rangeOfString:options: with RegularExpressionSearch as option. This in Swift.

The 2nd way is cleaner and simpler to implement.

The method method definition in Swift

func rangeOfString(_ aString: String!,options mask: NSStringCompareOptions) -> NSRange

You can use it with regex matching as:

let myStringToBeMatched = "ThisIsMyString"
let myRegex = "ing$"
if let match = myStringToBeMatched.rangeOfString(myRegex, options: .RegularExpressionSearch){
    println("(myStringToBeMatched) is matching!")
}

Here's Apple's documentation on rangeOfString()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...