Is there a way to achieve right-to-left behavior in Swift's new Regex?

Hello Swift Community,

As a newbie to Swift, I've been exploring the new Regex capabilities introduced last year. I have a question regarding the right-to-left behavior of regular expressions, similar to the RegexOptions.RightToLeft option in C#:

By default, the regular expression engine searches from left to right. You can reverse the search direction by using the RegexOptions.RightToLeft option. The right-to-left search automatically begins at the last character position of the string. For pattern-matching methods that include a starting position parameter, such as Regex.Match(String, Int32), the specified starting position is the index of the rightmost character position at which the search is to begin.

This behavior is particularly useful when matching patterns from the end of the string or when using starting position parameters.

However, I'm having trouble finding an equivalent approach in Swift's new Regex. The firstMatch(of:) method seems to match from left to right by default, and I haven't come across a direct option to change the search direction.

For example:

let regexYearDigit = try! Regex("\\d{4}").dotMatchesNewlines().dotMatchesNewlines()
let name = "Test (2021) - January 2019.pdf"
if let yearMatches = name.firstMatch(of: regexYearDigit){
    print(yearMatches.0)
    let updatedName = name.replacing(regexYearDigit, with: "2023")
}

I would like to get the 2019 value instead 2021 and change by 2023.

Thank you in advance for your guidance and assistance!

Best regards,

1 Like

How about name.matches(of: regexYearDigit).last instead of name.firstMatch(of: regexYearDigit)?