Reputation: 13
I want to get the characters using regex
I want to get "CDE"
var results : NSMutableArray;
var baseString = "ABCDEFG"
var regexp = NSRegularExpression(pattern: "AB.*?FG", options: nil, error: nil)
var match : NSArray = regexp.matchesInString(baseString, options: nil, range: NSMakeRange(0,countElements(baseString)));
for matches in match {
results.addObject(sampleString.substringWithRange(matches.rangeAtIndex(2)));
}
println(results);//print"CDE"
but I get error. ERROR→
results.addObject(sampleString.substringWithRange(matches.rangeAtIndex(2)));
NSRange' is not convertible to 'Range<String.Index>'
my english isn't good.sorry.. please help me...
Upvotes: 1
Views: 407
Reputation: 112875
The regular expression is incorrect, the match will be the entire string. Instead use: (?<=AB).*?(?=FG).
Documantation: ICU User Guide Regular Expressions
Notes:
(?<=AB) means preceded by AB
(?=FG) means followed by FG
These do not capture the matched portion.
Example code:
var baseString = "ABCDEFG"
var pattern = "(?<=AB).*?(?=FG)"
if let range = baseString.rangeOfString(pattern, options: .RegularExpressionSearch) {
let found = baseString.substringWithRange(range)
println("found: \(found)")
}
Output:
found: CDE
Upvotes: 5