【问题标题】:Swift range of substring - search string with wildcard子字符串的 Swift 范围 - 使用通配符搜索字符串
【发布时间】:2017-07-17 08:25:51
【问题描述】:

是否可以使用通配符在另一个字符串中搜索字符串? 我想找到 ""text1" = "text2"" 的出现,其中 text1 和 text2 可以是任何字符串。

我的初始字符串是

“这是我的字符串。这个字符串包括“text1”=“text2”等等”

搜索时我不知道 text1 和 text2。 我想过类似 """ = """ 但没有结果。

编辑: 让我尝试在其他示例中进行解释。 我有 *.swift 文件,其中有几个 locX 扩展名

        labelPatternForExpresion.stringValue = "labelPatternForExpresion".locX(withComment: "comment one")
    labelPath.stringValue = "labelPathToProject".locX(withComment: "comment six")
    labelHeader.stringValue = "labelFileHeader".locX(withComment: "no comment")
    btnFromFile.title = "btnFromFile".locX(withComment: "empty comment")
    btnCancel.title = "btnCancel".locX(withComment: "")

我需要遍历文件并找到所有键注释对:

“labelPatternForExpresion”-“评论一个”

“labelPathToProject”-“评论六”

........

........

"btnCancel" - ""

【问题讨论】:

  • 很可能 swift 可以像许多其他当前编程语言一样使用正则表达式。

标签: search swift3 nsstring substring wildcard


【解决方案1】:

假设你的模式是:

"textA" - "textB"

并且您想要捕获textAtextB。使用NSRegularExpression

let str = "\"labelPatternForExpresion\" - \"comment one\""

// NSRegularExpression still deals in NSString so let's make a copy to 
// lessen the pain later
let nsStr = str as NSString
let regex = try! NSRegularExpression(pattern: "\"(.+)\" - \"(.+)\"", options: [])

if let match = regex.firstMatch(in: str, options: [], range: NSMakeRange(0, nsStr.length)) {
    let lhs = nsStr.substring(with: match.rangeAt(1))
    let rhs = nsStr.substring(with: match.rangeAt(2))
    print(lhs)
    print(rhs)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多