【问题标题】:How to use regex to split string into groups of identical characters?如何使用正则表达式将字符串拆分为相同字符的组?
【发布时间】:2018-06-16 16:00:57
【问题描述】:

我得到一个这样的字符串:

var string = "AAAAAAABBBCCCCCCDD"

并且喜欢将字符串拆分成这种格式的数组(same characters --> same group使用正则表达式

Array: "AAAAAAA", "BBB", "CCCCCC", "DD"

这是我目前得到的,但我无法真正让它发挥作用。


var array = [String]()
var string = "AAAAAAABBBCCCCCCDD"
let pattern = "\\ b([1,][a-z])\\" // mistake?!
let regex = try! NSRegularExpression(pattern: pattern, options: [])

array = regex.matchesInString(string, options: [], range: NSRange(location: 0, length: string.count))

【问题讨论】:

  • 请注意,将string.count 传递给 NSRange 是错误的,并且可能导致包含“扩展字形簇”的字符串出现错误结果或崩溃。

标签: regex swift string


【解决方案1】:

您可以通过“反向引用”来实现,比较 NSRegularExpression:

\n

返回参考。匹配任何匹配的第 n 个捕获组。 n 必须是一个 ≥ 1 且 ≤ 模式中捕获组总数的数字。

示例(使用来自Swift extract regex matches 的实用方法):

let string = "AAAAAAABBBCCCCCCDDE"
let pattern = "(.)\\1*"

let array = matches(for: pattern, in: string)
print(array)
// ["AAAAAAA", "BBB", "CCCCCC", "DD", "E"]

模式匹配任意字符,后跟零个或多个 相同字符的出现。如果你只对 重复单词字符使用

let pattern = "(\\w)\\1*"

改为。

【讨论】:

    【解决方案2】:

    您可以通过answer 使用此功能来实现这一点:

    func matches(for regex: String, in text: String) -> [String] {
    
        do {
            let regex = try NSRegularExpression(pattern: regex)
            let results = regex.matches(in: text,
                                        range: NSRange(text.startIndex..., in: text))
            return results.map {
                String(text[Range($0.range, in: text)!])
            }
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }
    

    (.)\\1+ 传递为regexAAAAAAABBBCCCCCCDD 传递为text,如下所示:

    let result = matches(for: "(.)\\1+", in: "AAAAAAABBBCCCCCCDD")
    print(result) // ["AAAAAAA", "BBB", "CCCCCC", "DD"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 2015-08-22
      相关资源
      最近更新 更多