far*_*s97 0 arrays string ios swift
func findSrcs(_ content: String) {
if let match = content.range(of: """
(?<=src=")[^"]+
""", options: .regularExpression) {
print(content.substring(with: match))
}
}
Run Code Online (Sandbox Code Playgroud)
上面的函数需要返回srchtml 字符串中的所有 s。“内容”是 HTML 字符串。
函数可以工作,但仅打印内容中第一个图像的 src。怎样才能全部抓住呢?
您需要使用类似于本文中使用的 while 条件手动查找字符串中出现的所有情况,并获取字符串子序列而不是其范围:
func findSrcs(_ content: String) -> [Substring] {
let pattern = #"(?<=src=")[^"]+"#
var srcs: [Substring] = []
var startIndex = content.startIndex
while let range = content[startIndex...].range(of: pattern, options: .regularExpression) {
srcs.append(content[range])
startIndex = range.upperBound
}
return srcs
}
Run Code Online (Sandbox Code Playgroud)
游乐场测试:
let content = """
<span>whatever</span>
<img src="smiley.gif" alt="Smiley face">
<span>whatever</span>
<img src="stackoverflow.jpg" alt="Stack Overflow">
"""
print(findSrcs(content))
Run Code Online (Sandbox Code Playgroud)
这将打印
[“笑脸.gif”,“stackoverflow.jpg”]
| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |