我有从服务器返回的 XML 错误,错误的感兴趣部分的片段如下:
...
<p class="break-long-words trace-message">SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "name" violates not-null constraint<br />
DETAIL: Failing row contains (165, null, null, 11, null, 2018-04-19 03:01:48, null, f, 6).</p>
...
由于这种情况在开发过程中经常发生,因此我希望能够更轻松地扫描此特定错误消息并将其报告给后端团队。因此,从上面的错误中,我得出结论,我可以自信地获取以 SQLSTATE
开头的子字符串。并在 </p>
之前结束。所以清理后的错误将是:
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "name" violates not-null constraint<br />
DETAIL: Failing row contains (165, null, null, 11, null, 2018-04-19 03:01:48, null, f, 6).
问题是,如何在 Swift 中做到这一点? XML 错误不仅仅如此。我只是把兴趣点删掉了。但会有过多的<p></p>
标签。
最佳答案
使用 https://stackoverflow.com/a/32306142/300392 中找到的扩展我已经实现了自己的解决方案:
if xml.contains("</p>") {
let beginIndex = xml.index(of: "SQLSTATE")!
let result1 = String(xml[beginIndex...]);
let endIndex = result1.index(of: "</p>")!;
let endIndexBefore = result1.index(before: endIndex);
let result2 = String(result1[...endIndexBefore]);
print ("SQL ERROR: \(result2)");
}
关于ios - 如何在iOS中获取两个已知子字符串之间的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49912138/