我在Swift中遇到一些正则表达式问题;我已经环顾四周,但似乎无法正常工作。我已将Swift extract regex matches中的matches(for:in)
方法放入代码中。
我的测试字符串中有文本,内容为"SOURCEKEY:B"
,我想提取“ B”。因此,我将"SOURCEKEY:([A-Z])"
传递到matches(for:in:)
中,但结果是完整的字符串"SOURCEKEY:B"
。我在做什么错了?
顺便说一下,我的代码(尽管我想您需要知道的只是我正在尝试的表达式)
func testRegEx() {
let text = getTextFor("Roll To Me")!
XCTAssertTrue(text.contains("Look around your world")) // passes
XCTAssertTrue(text.contains("SOURCEKEY:")) // passes
let expression = "SOURCEKEY:([A-Z])(?s.)DESTKEY:([A-Z])(?s.)"
let matchesArray = matches(for: expression, in: text) // matchesArray[0] = "SOURCEKEY:"
}
这是第一部分。我想要的最终表达式将分解这样的文本(我要返回的所有文本均在下面加上反引号):
SOURCEKEY:B
a bunch of text
more lines of text
these go in the 2nd returned value, where "B" is the first returned value
everything up to...
DESTKEY:E
a bunch more text
these go in the 4th returned value, where "E" is the third returned value
this includes the remainder of the string after that 3rd value
我已经成功地在没有正则表达式的情况下成功完成了此操作,以获得上述四个元素的sourceKey
,origText
,destKey
和expectedText
:
let allComponents = text.components(separatedBy: "KEY:")
let origTextComponents = allComponents[1].split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: false).map{String($0)}
let sourceKey = origTextComponents[0]
let origText = origTextComponents[1].replacingOccurrences(of: "DEST", with: "")
let destTextComponents = allComponents[2].split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: false).map{String($0)}
let destKey = destTextComponents[0]
let expectedText = destTextComponents[1]
但是我想正确的正则表达式会将其缩减为一行,我可以在下一行中访问其元素以初始化结构。
答案 0 :(得分:1)
这是获取正则表达式的捕获组的示例。索引3处的组是(.|\\n)
表达式,用于跨行边界搜索。
let string = """
SOURCEKEY:B
a bunch of text
more lines of text
these go in the 2nd returned value, where "B" is the first returned value
everything up to...
DESTKEY:E
a bunch more text
these go in the 4th returned value, where "E" is the third returned value
this includes the remainder of the string after that 3rd value
"""
let pattern = "SOURCEKEY:([A-Z])\\s+((.|\\n)*)DESTKEY:([A-Z])\\s+((.|\\n)*)"
do {
let regex = try NSRegularExpression(pattern: pattern)
if let match = regex.firstMatch(in: string, range: NSRange(string.startIndex..<string.endIndex, in: string)) {
print(string[Range(match.range, in: string)!]) // prints the entire match ignoring the captured groups
print(string[Range(match.range(at:1), in: string)!])
print(string[Range(match.range(at:2), in: string)!])
print(string[Range(match.range(at:4), in: string)!])
print(string[Range(match.range(at:5), in: string)!])
} else {
print("Not Found")
}
} catch {
print("Regex Error:", error)
}