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
188 views
in Technique[技术] by (71.8m points)

ios - Swift regex: does a string match a pattern?

In Swift, what is a simple way to see if a string matches a pattern?

Pseudocode examples:

if string matches pattern ...

if string =~ pattern ...

(I have read the Swift docs and haven't seen a regex capability. I've read about adding a new =~ operator which is a good idea yet more complex than I'd like because this is for a teaching project. I have tried rangeOfString but get the error: 'String' does not have a member 'rangeOfString'. I am looking for a Swift solution, i.e. not typing NSRegularExpression. I do not need to do anything with the match result data.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Swift version 3 solution:

if string.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil ...

Swift version 2 solution:

if string.rangeOfString(pattern, options: .RegularExpressionSearch) != nil ...

Example -- does this string contain two letter "o" characters?

"hello world".rangeOfString("o.*o", options: .RegularExpressionSearch) != nil

Note: If you get the error message 'String' does not have a member 'rangeOfString', then add this before: import Foundation. This is because Foundation provides the NSString methods that are automatically bridged to the Swift String class.

import Foundation

Thanks to Onno Eberhard for the Swift 3 update.


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

...