问题描述
在Swift中,查看字符串是否与模式匹配的简单方法是什么?
In Swift, what is a simple way to see if a string matches a pattern?
伪代码示例:
if string matches pattern ...
if string =~ pattern ...
(我已阅读Swift文档并且没有看到正则表达式功能。我读过有关添加新 =〜$ c的内容$ c>运算符这是一个好主意但比我想要的更复杂,因为这是一个教学项目。我试过
rangeOfString
但得到错误:'String'我没有成员'rangeOfString'。我正在寻找一个Swift解决方案,即不输入NSRegularExpression。我不需要对匹配结果数据做任何事情。)
(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.)
推荐答案
Swift版本3解决方案:
Swift version 3 solution:
if string.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil ...
Swift版本2解决方案:
Swift version 2 solution:
if string.rangeOfString(pattern, options: .RegularExpressionSearch) != nil ...
示例 - 执行此字符串包含两个字母o字符?
Example -- does this string contain two letter "o" characters?
"hello world".rangeOfString("o.*o", options: .RegularExpressionSearch) != nil
注意:如果收到错误消息'String'没有成员'rangeOfString'
,然后在之前添加: import Foundation
。这是因为
Foundation提供了自动桥接到Swift String类的NSString方法。
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
感谢Onno Eberhard对Swift 3的更新。
Thanks to Onno Eberhard for the Swift 3 update.
这篇关于Swift正则表达式:字符串匹配模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!