2017-02-26 120 views
1

是否可以使用通配符在另一个字符串内搜索字符串? 我想查找“”text1“=”text2“的出现位置,其中text1和text2可以是任何字符串。子串的快速范围 - 带通配符的搜索字符串

我最初的字符串是

“这是我的字符串。这个字符串包括‘text1’中的=‘文本2’等等”

我不知道文本1和文本搜索时。 我曾想过类似“”“=”“”但没有结果。编号: 让我试着解释一下其他的例子。 我有* .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” - “”

+1

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

回答

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) 
}