ios Swift 正则表达式:字符串是否与模式匹配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29784447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift regex: does a string match a pattern?
提问by joelparkerhenderson
In Swift, what is a simple way to see if a string matches a pattern?
在 Swift 中,查看字符串是否与模式匹配的简单方法是什么?
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.)
(我已经阅读了 Swift 文档,但还没有看到正则表达式功能。我读过关于添加一个新的=~
运算符,这是一个好主意,但比我想要的更复杂,因为这是一个教学项目。我试过了,rangeOfString
但是得到错误:'String' 没有成员 'rangeOfString'。我正在寻找一个 Swift 解决方案,即不输入 NSRegularExpression。我不需要对匹配结果数据做任何事情。)
回答by joelparkerhenderson
Swift version 3 solution:
Swift 版本 3 解决方案:
if string.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil ...
Swift version 2 solution:
Swift 版本 2 解决方案:
if string.rangeOfString(pattern, options: .RegularExpressionSearch) != nil ...
Example -- does this string contain two letter "o" characters?
示例 -- 此字符串是否包含两个字母“o”字符?
"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.
注意:如果您收到错误消息'String' does not have a member 'rangeOfString'
,请在此之前添加:import Foundation
。这是因为 Foundation 提供了自动桥接到 Swift String 类的 NSString 方法。
import Foundation
Thanks to Onno Eberhard for the Swift 3 update.
感谢 Onno Eberhard 为 Swift 3 更新。
回答by Onno Eberhard
The solutions mentioned above didn't work for me anymore, so I'm posting my solution here (I used an extension for String):
上面提到的解决方案不再适合我,所以我在这里发布我的解决方案(我使用了 String 的扩展名):
extension String {
func matches(_ regex: String) -> Bool {
return self.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
}
}
Example:
例子:
if str.matches("^[a-zA-Z0-9._-]{1,30}$") {
//...
}
回答by David Berry
To get the syntax you actually ask about, you can easily define a new operator which wraps the bridged NSString
functionality:
要获得您实际询问的语法,您可以轻松定义一个包含桥接NSString
功能的新运算符:
infix operator =~ {}
func =~(string:String, regex:String) -> Bool {
return string.rangeOfString(regex, options: .RegularExpressionSearch) != nil
}
"abcd" =~ "ab*cd"
"abcd" =~ "abcde+"
回答by P J Szekszardi
In Swift 4.2the following doesn't return nil even if the string does not match the pattern:
在Swift 4.2 中,即使字符串与模式不匹配,以下内容也不会返回 nil:
string.range(of: regex, options: .regularExpression, range: nil, locale: nil)
As Xcode suggests:
正如 Xcode 所建议的:
Comparing non-optional value of type 'NSRange' (aka '_NSRange') to nil always returns true
将“NSRange”(又名“_NSRange”)类型的非可选值与 nil 进行比较总是返回 true
Therefore what I ended up using is:
因此,我最终使用的是:
if string.range(of: regex, options: .regularExpression)
.location != NSNotFound {
// do stuff if string matches regexp
}
回答by Gary Davies
This will return whether a string matches a pattern
这将返回字符串是否与模式匹配
eg. matchesPattern(text: "sd56Yz", pattern: "[a-zA-Z0-9]+") true
例如。匹配模式(文本:“sd56Yz”,模式:“[a-zA-Z0-9]+”)真
eg. matchesPattern(text: "sd56$Yz", pattern: "[a-zA-Z0-9]+") false
例如。匹配模式(文本:“sd56$Yz”,模式:“[a-zA-Z0-9]+”)假
func matchesPattern(text: String?, pattern: String?) -> Bool {
guard hasValue(text) && hasValue(pattern) else {
return false
}
let range = text!.rangeOfString(pattern!, options: .RegularExpressionSearch)
guard range != nil else {
return false
}
let rangeString = text?.substringWithRange(range!)
return areEqual(text, string2: rangeString)
}