RegExp结果不是我的预期

时间:2016-12-23 03:16:32

标签: ios regex swift regular-language

我的regExp没有得到正确的结果,我找不到错误的地方。

    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)-,但我的regExp结果是控制台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 }`

1 个答案:

答案 0 :(得分:1)

您需要进行区分大小写的匹配。 将选项从.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: "-$1-").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) { "-\($0.lowercased())-" }
print("Uppercase characters replaced: \(replaced)")