Created
June 15, 2014 17:06
-
-
Save AlexanderNey/96ec206a51bd2363a345 to your computer and use it in GitHub Desktop.
Swift String extension to ease working with regular expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// String+RegularExpression.swift | |
// | |
// Created by Alexander Ney on 15/06/2014. | |
// Copyright (c) 2014 Alexander Ney. All rights reserved. | |
// | |
import Foundation | |
// Compate String related Ranges | |
@infix func == (left: Range<String.Index>, right: Range<String.Index>) -> Bool | |
{ | |
return (left.startIndex == right.startIndex) && (left.endIndex == right.endIndex) | |
} | |
extension String | |
{ | |
// Full range of the string | |
var range : Range<String.Index> | |
{ | |
return Range(start: self.startIndex, end:self.endIndex) | |
} | |
// Returns ture if string matches the reuglar expression | |
func matchesPattern(pattern: String) -> Bool | |
{ | |
return self.rangeOfString(pattern, options: NSStringCompareOptions.RegularExpressionSearch) == self.range | |
} | |
// Returns an Array of tuples (range, matched string) | |
func substringsMatchingPattern(pattern: String) -> Array<(Range<String.Index>,String)> | |
{ | |
var matchingSubStrings : Array<(Range<String.Index>,String)> = [] | |
var range : Range<String.Index> | |
var searchRange = self.range | |
do { | |
range = self.rangeOfString(pattern, options: .RegularExpressionSearch, range: searchRange) | |
if !range.isEmpty | |
{ | |
matchingSubStrings += (range, self.substringWithRange(range)) | |
} | |
searchRange.startIndex = range.endIndex | |
} while !range.isEmpty | |
return matchingSubStrings | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
get all substrings matching ${ ... } of a string and enumerate them: