Lesson
1. Match string using regular expression
Use regular expression pattern \\d{3}-(\\d{4})-\\d{2} to match string 123-4567-89
Return match result: ’"123-4567-89" and ’4567’
2. Replace string using regular expression pattern
Use regular expression pattern (\\d+)-(\\d+)-(\\d+) to match string 123-4567-89
Use pattern string "$3-$1-$2" to replace match result, return result "89-123-4567".
3. Replace string using regular expression callback
Use regular expression pattern \\d+ to match string 123-4567-89
Replace match result (three numbers) by reversing them, return result "321-7654-98".
4. Split string using regular expression
Use regular expression pattern %(%begin|next|end)% to split string "%begin%hello%next%world%end%".
Return split result: "hello" and "world" in between the regular expression delimiters.
Swift
import Foundation
let s = "123-4567-89,987-6543-21"
let r = try NSRegularExpression(pattern: #"\d{3}-(\\d{4})-\\d{2}"#)
let results = r.matches(in: s, range: NSRange(s.startIndex..., in: s))
for (i, m) in results.enumerated() {
for j in 0..
let r2 = try NSRegularExpression(pattern: #"(\d+)-(\d+)-(\d+)"#)
let s2 = r2.stringByReplacingMatches(in: s, range: NSRange(s.startIndex..., in: s), withTemplate: "$3-$1-$2")
print(s2)
let r3 = try NSRegularExpression(pattern: #"\d+"#)
let results2 = r3.matches(in: s, range: NSRange(s.startIndex..., in: s))
var s3 = s
for i in (0..
// https://stackoverflow.com/questions/25818197/how-to-split-a-string-in-swift
extension String {
func split(regex pattern: String) -> [String] {
guard let re = try? NSRegularExpression(pattern: pattern, options: [])
else { return [] }
let nsString = self as NSString // needed for range compatibility
let stop =
let modifiedString = re.stringByReplacingMatches(
in: self,
range: NSRange(location: 0, length: nsString.length),
withTemplate: stop)
return modifiedString.components(separatedBy: stop)
}
}
let r4 = "%(begin|next|end)%"
let s4 = "%begin%hello%next%world%end%"
print(s4.split(regex: r4))
group 0,0 : 123-4567-89
group 0,1 : 4567
group 1,0 : 987-6543-21
group 1,1 : 6543
89-123-4567,21-987-6543
321-7654-98,789-3456-12
["", "hello", "world", ""]