Post

Replies

Boosts

Views

Activity

Reply to Regex Builder error message???
I got this working by using the Repeat component instead of Capture in hourReg and minuteReg. I'm not sure why that should matter, but Repeat is cleaner. I also got the transform to work by returning a Substring in the transform: of the ampmReg Regex. import Cocoa import Foundation import RegexBuilder let hourRef = Reference<Substring>() let minuteRef = Reference<Substring>() let hourReg = Regex { Capture(as: hourRef) { ChoiceOf { Repeat(.digit, count: 2) Repeat(.digit, count: 1) } } } let minuteReg = Regex { Capture(as: minuteRef) { ChoiceOf { Repeat(.digit, count: 2) Repeat(.digit, count: 1) } } } let ampmRef = Reference<Substring>() let ampmReg = Regex { Capture(as: ampmRef) { ChoiceOf { One("am") One("pm") One("a.m.") One("p.m.") } } transform: { return Substring($0.lowercased()) } }.ignoresCase() let timeWithoutSec = Regex { hourReg One(":") minuteReg ZeroOrMore(.whitespace) ampmReg }.ignoresCase() let possibleTime = "1:20pM" let timeMatchWithout = possibleTime.firstMatch(of: timeWithoutSec) However, this version requires an 'am', 'pm' , 'a.m.', or 'p.m.' to be part of the string. To make this optional I tried to change the timeWithoutSec Regex to: let timeWithoutSec = Regex { hourReg One(":") minuteReg ZeroOrMore(.whitespace) ZeroOrMore { ampmReg } }.ignoresCase() But this results in that odd Regex.Match optional storedCapture contains no some error message. How can I make the ampmReg optional?
Topic: Programming Languages SubTopic: Swift Tags:
May ’24