Jump to content

Regular expressions: Difference between revisions

→‎{{header|Objective-C}}: added nsregularexpression (ios only)
(→‎{{header|Objective-C}}: added nsregularexpression (ios only))
Line 543:
}</lang>
Unfortunately this method cannot find the location of the match or do substitution.
 
===NSRegularExpression===
{{works with|iOS|4.0+}}
Test
<lang objc>NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"string$"
options:0
error:NULL];
NSString *str = @"I am a string";
if ([regex rangeOfFirstMatchInString:str
options:0
range:NSMakeRange(0, [str length])
].location != NSNotFound) {
NSLog(@"Ends with 'string'");
}</lang>
 
Loop through matches
<lang objc>for (NSTextCheckingResult *match in [regex matchesInString:str
options:0
range:NSMakeRange(0, [str length])
]) {
// 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 objc>NSString *orig = @"I am the original string";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"original"
options:0
error:NULL];
NSString *result = [regex stringByReplacingMatchesInString:orig
options:0
range:NSMakeRange(0, [orig length])
withTemplate:@"modified"];
NSLog(@"%@", result);</lang>
 
=={{header|OCaml}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.