Anonymous user
Regular expressions: Difference between revisions
added swift
No edit summary |
(added swift) |
||
Line 1,943:
print ("matched at position " ^ Int.toString pos ^ "\n")
end;</lang>
=={{header|Swift}}==
===RegularExpressionSearch===
Test
<lang swift>import Foundation
let str = "I am a string"
if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) {
println("Ends with 'string'")
}</lang>
Substitute (undocumented)
<lang swift>import Foundation
let orig = "I am the original string"
let result = orig.stringByReplacingOccurrencesOfString("original", withString: "modified", options: .RegularExpressionSearch)
println(result)</lang>
===NSRegularExpression===
Test
<lang swift>import Foundation
if let regex = NSRegularExpression(pattern: "string$", options: nil, error: nil) {
let str = "I am a string"
if let result = regex.firstMatchInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {
println("Ends with 'string'")
}
}</lang>
Loop through matches
<lang swift> for x in regex.matchesInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {
let match = x as! NSTextCheckingResult
// match.range gives the range of the whole match
// match.rangeAtIndex(i) gives the range of the i'th capture group (starting from 1)
}</lang>
Substitute
<lang swift>import Foundation
let orig = "I am the original string"
if let regex = NSRegularExpression(pattern: "original", options: nil, error: nil) {
let result = regex.stringByReplacingMatchesInString(orig, options: nil, range: NSRange(location: 0, length: count(orig.utf16)), withTemplate: "modified")
println(result)
}</lang>
=={{header|Tcl}}==
|