问题
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