i want know if it's possible detect and delete a date in string format in a text, like this:
Title 31 December 2012
Title December 2012
Title 31-12-12
Title (31-12-12)
in this three example in all cases i want delete all and remain only the world "Title", i found this method for example to delete the text inside the parentheses:
searchText = [searchText stringByReplacingOccurrencesOfString:@" \\([^()]*\\)" withString:@"" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, [searchText length])];
and i can delete this (31-12-12), but i can't understand how i can do for the other cases...
Combine into one RE:
NSString *reText = @" ((\\d{2} )?\\w+ \\d{4})|(\\(?\\d{2}-\\d{2}-\\d{2}\\)?)";
Note that this is really comprised of two REs or'ed together:
(\\d{2} )?\\w+ \\d{4}
and
\\(?\\d{2}-\\d{2}-\\d{2}\\)?
See NSRegularExpression Class Reference
NSArray *testList = @[
@"Title 31 December 2012",
@"Title December 2012",
@"Title 31-12-12",
@"Title (31-12-12)"
];
NSString *reText = @"( (\\d{2} )?\\w+ \\d{4})|( \\(?\\d{2}-\\d{2}-\\d{2}\\)?)";
for (NSString *test in testList) {
NSString *result = [test
stringByReplacingOccurrencesOfString:reText
withString:@""
options:NSRegularExpressionSearch|NSCaseInsensitiveSearch
range:NSMakeRange(0, [test length])];
NSLog(@"result: '%@' test: '%@'", result, test);
}
NSLog output:
result: 'Title' test: 'Title 31 December 2012'
result: 'Title' test: 'Title December 2012'
result: 'Title' test: 'Title 31-12-12'
result: 'Title' test: 'Title (31-12-12)'
You have to use a different regex.
This one should catch all your 4 cases.
searchText = [searchText stringByReplacingOccurrencesOfString:@"\\W+((\\(?\\d+(-|\\.)\\d+(-|\\.)\\d+\\)?)|((\\d+ )?\\w+ \\d+))" withString:@"" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, [searchText length])];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With