[英]iOS Swift - How to match a string that is “like” another string? i.e. “http” is like “http://”
I created a URL Validation function that validates for URL as text is entered by a user into a text field.我创建了一个 URL 验证函数,用于在用户将文本输入到文本字段时验证 URL。
However, in an effort to save performance and memory, I want to ignore entries that may contain common URL prefixes:但是,为了节省性能和内存,我想忽略可能包含常见 URL 前缀的条目:
(i.e. http://, http://www, www, etc)
With that said, I want to be able to "smartly" ignore text that may MATCH one of these URL prefixes:话虽如此,我希望能够“聪明地”忽略可能与以下 URL 前缀之一匹配的文本:
["http://www", "https://www", "www"]
i.e. If a user has typed "htt", it should be ignored since it is a substring of "http://www" or "https://www"
What is the best way to check if a string may match provided prefixes but not necessarily are equal?检查字符串是否可以匹配提供的前缀但不一定相等的最佳方法是什么?
From the Swift Programming Language Guide, you can use the hasPrefix method.从 Swift Programming Language Guide,您可以使用 hasPrefix 方法。
Example:例子:
if userString.hasPrefix("http") {
// do something with userString
}
Source: Swift Programming Language Guide来源: Swift 编程语言指南
Ok, figured it out.好的,想通了。 Had to use 'rangeOfString' function and check if user's text was in my control text.
必须使用“rangeOfString”函数并检查用户的文本是否在我的控制文本中。
Code:代码:
let prefixes = ["http://www.", "https://www.", "www."]
for prefix in prefixes
{
if ((prefix.rangeOfString(urlString!, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)) != nil){
completion(success: false, urlString: nil, error: "Url String was prefix only")
return
}
}
a simple partial comparison can be achieved by using .contains
使用
.contains
可以实现简单的部分比较
let string = "hello Swift"
if string.contains("Swift") {
print("exists")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.