按大写单词/字符和数字拆分字符串 [英] Split string by uppercase words/chars and numerics

查看:88
本文介绍了按大写单词/字符和数字拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the string like this - "H2SO4liH2", i need to split this string by uppercase elements and numerics. At the out i need to get array like this "H2", "S", "O4", "Li", "H2" or "H", "2", "S", "O", "4", "Li", "H", "2"

推荐答案

这使用了toheedNiaz的答案,但是在Swift上下文中:

This uses the pattern provided in toheedNiaz's answer but in a Swift context:

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)
}

这篇关于按大写单词/字符和数字拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆