RegExp 结果不是我的预期

RegExp result is not my expected

我的正则表达式没有得到正确的结果,我找不到错误的地方。

    let ori_str = "abcXabcYabcZ"  // there are 3 Capital character

    let pattern = "[A-Z]"

    let regular = try!NSRegularExpression(pattern: pattern, options: .caseInsensitive)

    let results = regular.matches(in: ori_str, options: .reportProgress , range: NSMakeRange(0, ori_str.characters.count))
    print("results have: \(results.count) count")  // log  'result have: 12 count'  why 12 without 3 ???

我想获取大写字符,然后将它们替换为 -(the Capital character's lower character)-,但我的正则表达式的结果是控制台 12 个大写字符。

1)你看,应该是3,哪里错了?
2) 如何将大写字符替换为 -(the capital's lower character)- ?


加法-1

以下所有NSRegularExpression.Options

    public static var caseInsensitive: NSRegularExpression.Options { get }

    public static var allowCommentsAndWhitespace: NSRegularExpression.Options { get }

    public static var ignoreMetacharacters: NSRegularExpression.Options { get }

    public static var dotMatchesLineSeparators: NSRegularExpression.Options { get }

    public static var anchorsMatchLines: NSRegularExpression.Options { get }

    public static var useUnixLineSeparators: NSRegularExpression.Options { get }

    public static var useUnicodeWordBoundaries: NSRegularExpression.Options { get }`

您需要进行区分大小写的匹配。 将选项从 .caseInsensitive 更改为 [].

NSRegularExpression.Options 是一个 OptionSet,它允许指定零个或多个值。当传递零或多于一时,使用数组文字语法。 参见:https://developer.apple.com/reference/swift/optionset

let ori_str = "abcXabcYabcZ"  // there are 3 Capital character
let pattern = "[A-Z]"
let regular = try!NSRegularExpression(pattern: pattern, options: [])
let results = regular.matches(in: ori_str, options: .reportProgress, range: NSMakeRange(0, ori_str.characters.count))
print("results have: \(results.count) count")

关于您的第二个标准,使用正则表达式组将涵盖:

let ori_str = "abcXabcYabcZ"  // there are 3 Capital character
let pattern = "([A-Z])"
let regular = try!NSRegularExpression(pattern: pattern)
let replaced = regular.stringByReplacingMatches(
    in: ori_str, options: [],
    range: NSMakeRange(0, ori_str.characters.count),
    withTemplate: "--").lowercased()
print("Uppercase characters replaced: \(replaced)")

对于更高级的内容,您需要为每个匹配添加额外的自定义代码:

extension String {
    func replace(regex: NSRegularExpression, with replacer: (_ match:String)->String) -> String {
        let str = self as NSString
        let ret = str.mutableCopy() as! NSMutableString

        let matches = regex.matches(in: str as String, options: [], range: NSMakeRange(0, str.length))
        for match in matches.reversed() {
            let original = str.substring(with: match.range)
            let replacement = replacer(original)
            ret.replaceCharacters(in: match.range, with: replacement)
        }
        return ret as String
    }
}

let ori_str = "abcXabcYabcZ"  // there are 3 Capital character
let pattern = "[A-Z]"
let regular = try!NSRegularExpression(pattern: pattern)
let replaced = ori_str.replace(regex: regular) { "-\([=12=].lowercased())-" }
print("Uppercase characters replaced: \(replaced)")