带有变量(不固定)字符串子组件的 Swift Regex

l -*_*c l 4 regex swift

是否可以Regex使用可变(非固定)组件创建可重用的 Swift 5.8+ 模式?如果是,怎么办?

\n

从概念上讲,考虑将关键字变量用作正则表达式的一部分的用例。这类似于String类型中的插值。

\n
func example(keyword: String) {\n    // non-functional concept shorthand\n    var regex = /\xe2\x80\xa6\\(keyword)\xe2\x80\xa6/\n    // do something with regex \n}\n
Run Code Online (Sandbox Code Playgroud)\n

正则表达式文字很可能/\xe2\x80\xa6/没有支持这种方法的语法。\\(\xe2\x80\xa6) String并且,插值语法与正则表达式捕获语法的相似性可能存在问题(\xe2\x80\xa6)

\n

相反,可以以某种方式使用几种较新的(非NSRegularExpression)正则表达式定义方法中的任何一种来支持可变子String组件吗?

\n

Rob*_*ier 6

RegexBuilder 提供了一种便捷的方法来构建它。例如:

import RegexBuilder

let string = "prefixandthissuffix"

func example(keyword: String) {
    // non-functional concept shorthand
    var regex = Regex {
        "prefix"
        keyword
        "suffix"
    }

    if let match = string.wholeMatch(of: regex) {
        print(match.output)
    } else {
        print("\(keyword): nomatch")
    }
}

example(keyword: "andthis")  // prints match
example(keyword: "andthat")  // nomatch
Run Code Online (Sandbox Code Playgroud)

请注意,Regex每次需要更改关键字字符串时都需要重新构建。动态重建可以封装在函数中。

func quotedRegex(keyword: String) -> Regex<Substring> {
    let regex = Regex {
        /"/
        keyword
        /"/
    }
    return regex
}

let string = "{\"key1\":\"value\"}"
for word in ["key1", "KEY1", "key2"] {
    var regex = quotedRegex(keyword: word)
    regex = regex.ignoresCase() // transformed
    if let match = string.firstMatch(of: regex) {
        print("\(word) matched \(match.output)")
    } else {
        print("\(word) not matched")
    }
}

// print:
//   key1 matched "key1"
//   KEY1 matched "key1"
//   key2 not matched
Run Code Online (Sandbox Code Playgroud)