用大写单词/字符和数字分割字符串

时间:2018-03-28 16:40:10

标签: arrays swift string contains

我有这样的字符串 - “H2SO4liH2”,我需要用大写元素和数字来分割这个字符串。在外面,我需要得到像这样的数组 “H2”,“S”,“O4”,“Li”,“H2”或 “H”,“2”,“S”,“O”,“4”,“Li”,“H”,“2”

1 个答案:

答案 0 :(得分:0)

这使用了toheedNiaz的答案中提供的模式,但是在Swift环境中:

let string = "H2SO4LiH2"

let pattern = "[A-Z][^A-Z]*"
do {
    let regex = try NSRegularExpression(pattern: pattern)
    let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
    for match in matches {
        let range = Range(match.range, in: string)!
        print(string[range])
    }
} catch {
    print("Regex Error:", error)
}