I'm having trouble with some Regex in Swift; I've done some looking around but can't seem to get it to work. I've put the matches(for:in)
method from Swift extract regex matches into my code.
I have text in my test String that reads "SOURCEKEY:B"
and I want to extract the "B". So I pass "SOURCEKEY:([A-Z])"
into matches(for:in:)
but the result is the full string "SOURCEKEY:B"
. What am I doing wrong?
My code, by the way (although I think all you need to know is the expression I'm trying)
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:"
}
That's the first part. The ultimate expression I want will break up the text like this (all the text I want returned is backticked below):
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
I've managed to successfully do this without regex, to get sourceKey
, origText
, destKey
, and expectedText
for the 4 elements referenced above:
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]
But I imagine the correct regex would cut this down to one line, whose elements I could access to initialize a struct in my next line.