Regular expressions: Difference between revisions

Content added Content deleted
(→‎{{header|Objective-C}}: added nsregularexpression (ios only))
Line 543: Line 543:
}</lang>
}</lang>
Unfortunately this method cannot find the location of the match or do substitution.
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}}==
=={{header|OCaml}}==