对于给定的NSstring,我需要搜索一个ip地址并显示它。 下面是示例代码,但不知道它为什么不起作用。
字符串是
..
"Stories": [
{
"userId": "105304831528398207103",
"story": "some story",
"Likes": [
{user_id :"user id 1", user_name: "user name"},
.....
],
"_id": {
"$oid": "55c055af1875b0002572cf94"
}
}
]
..
函数searchIPString()
(SII_Bg
SII Bg
Disconnected ( User Disconnected )
N/A
SII_Bg_IP
SII Bg via Router
Connected (00:19:36)
191.30.33.55
N/A
)
但结果值为“0元素”,即使该字符串具有有效的IP地址。 请让我知道我哪里出错了。
感谢
答案 0 :(得分:1)
尝试按照模式搜索整个字符串,您不需要替换换行符
let pattern = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"
代码就像
let pattern = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"
do {
let string = "Your Text"
let regex = try NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matchesInString(string, options: [], range: NSRange(location: 0, length: string.characters.count))
} catch {
}
答案 1 :(得分:1)
你甚至可以简化正则表达式。做这样的事。
func searchIPString(string: String) -> [String]? {
let regex = "\\d{1,3}[.]\\d{1,3}[.]\\d{1,3}[.]\\d{1,3}"
do {
let regularExpresion = try NSRegularExpression(pattern: regex, options: .CaseInsensitive)
let matches = regularExpresion.matchesInString(string, options: .ReportCompletion, range: NSMakeRange(0, string.characters.count))
var matchingIPs = [String]()
let convertedString = string as NSString
matches.forEach { textCheckingResult in
let range = textCheckingResult.range
let foundIP = convertedString.substringWithRange(range) as String
matchingIPs.append(foundIP)
}
return matchingIPs
} catch let error as NSError{
print("Regular Expression Format is Wrong: \(error.localizedDescription)")
}
return []
}