ios - 如何在iOS中获取两个已知子字符串之间的子字符串?

标签 ios swift string

我有从服务器返回的 XML 错误,错误的感兴趣部分的片段如下:

... <p class="break-long-words trace-message">SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column &quot;name&quot; 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 &quot;name&quot; 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/

相关文章:

ios - swift 4 : Save and retrieve an array of custom objects (with nested custom objects) to UserDefaults

c++ - 为什么一个表达式中的 std::string 连接给出的结果与 char by char 的结果不同?

objective-c - Cocoa 的 NIB/XIB 混淆

iphone - UITableView 部分标题中的字体大小、字体颜色、阴影颜色和偏移量是多少?

ios - 如何找出SQLITE查询结果为NULL?

ios - 多次调用observeValueForKeyPath

ios - Xcode 6 Storyboard Unwind Segue with Swift 不连接退出

ios - 在 dispatch_async 中调用委托(delegate)方法

java - 什么时候在 stringbuilder/stringbuffer 上使用 string?

java - 2D 字符串数组转换为 2D Int 数组