I've created a regular expressions library for swift! Check it out here. I would appreciate some feedback. Here are some examples:
var inputText = "name: Chris Lattner"
// create the regular expression object
let regex = try Regex(
pattern: "name: ([a-z]+) ([a-z]+)",
regexOptions: [.caseInsensitive]
)
if let match = try inputText.regexMatch(regex) {
print("full match: '\(match.fullMatch)'")
print("first capture group: '\(match.groups[0]!.match)'")
print("second capture group: '\(match.groups[1]!.match)'")
// perform a replacement on the first capture group
inputText.replaceSubrange(
match.groups[0]!.range, with: "Steven"
)
print("after replacing text: '\(inputText)'")
}
// full match: 'name: Chris Lattner'
// first capture group: 'Chris'
// second capture group: 'Lattner'
// after replacing text: 'name: Steven Lattner'
let name = "Charles Darwin"
let reversedName = try name.regexSub(
#"(\w+) (\w+)"#,
with: "$2 $1"
// $1 and $2 represent the
// first and second capture group, respectively.
// $0 represents the entire match.
)
// reversedName = "Darwin Charles"
My library also supports naming the capture groups!. For example:
var inputText = "season 8, EPISODE 5; season 5, episode 20"
// create the regular expression object
let regex = try Regex(
pattern: #"season (\d+), Episode (\d+)"#,
regexOptions: [.caseInsensitive],
groupNames: ["season number", "episode number"]
// the names of the capture groups
)
let results = try inputText.regexFindAll(regex)
for result in results {
print("fullMatch: '\(result.fullMatch)'")
print("capture groups:")
for captureGroup in result.groups {
print(" \(captureGroup!.name!): '\(captureGroup!.match)'")
}
print()
}
let firstResult = results[0]
// perform a replacement on the first full match
inputText.replaceSubrange(
firstResult.range, with: "new value"
)
print("after replacing text: '\(inputText)'")
// fullMatch: 'season 8, EPISODE 5'
// capture groups:
// 'season number': '8'
// 'episode number': '5'
//
// fullMatch: 'season 5, episode 20'
// capture groups:
// 'season number': '5'
// 'episode number': '20'
//
// after replacing text: 'new value; season 5, episode 20'