Split string by uppercase words/chars and numerics

北城余情 提交于 2020-01-06 08:43:31

问题


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"


回答1:


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


来源:https://stackoverflow.com/questions/49539956/split-string-by-uppercase-words-chars-and-numerics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!