swiftregexreflectionswift-regexbuilder

How to convert a Swift 5.7 Regex back to a string?


It's pretty straightforward to convert a string to a regex:

let regex = try! Regex("foo")

But if I try to get the string back out of the regex, instead of foo, I get something like:

_StringProcessing.Regex<_StringProcessing.AnyRegexOutput>(program: _StringProcessing.Regex<_StringProcessing.AnyRegexOutput>.Program)

Mirrors are of marginal help here. It takes several levels of reflection to get anywhere:

let regexMirror = Mirror(reflecting: regex)
let program = regexMirror.children.first!.value // runtime type: Regex<AnyRegexOutput>.Program
let programMirror = Mirror(reflecting: program)
print(Array(programMirror.children))

[(label: Optional("tree"), value: _StringProcessing.DSLTree(root: _StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.concatenation([_StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.atom(_StringProcessing.DSLTree.Atom.char("f")), _StringProcessing.DSLTree._AST.ASTNode(ast: 「f」)), _StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.atom(_StringProcessing.DSLTree.Atom.char("o")), _StringProcessing.DSLTree._AST.ASTNode(ast: 「o」)), _StringProcessing.DSLTree.Node.convertedRegexLiteral(_StringProcessing.DSLTree.Node.atom(_StringProcessing.DSLTree.Atom.char("o")), _StringProcessing.DSLTree._AST.ASTNode(ast: 「o」))]), _StringProcessing.DSLTree._AST.ASTNode(ast: (「f」,「o」,「o」))))), (label: Optional("compileOptions"), value: _StringProcessing._CompileOptions(rawValue: 0)), (label: Optional("_loweredProgramStorage"), value: nil)]

This is something that gives the appearance of being parseable, but it's full of private types and things I don't particularly care about.

Is there a simple way to get the string representation of a regex?


Solution

  • There is an API to do this, but the bad news is that it’s currently private:

    let regex = /[a-z]/
    let pattern: String? = regex._literalPattern
    

    If you’re not forced to deal with Apple’s App Stores, it works great. See the declaration here.