Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect and Delete date string in a text

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...

like image 678
Piero Avatar asked Nov 16 '25 14:11

Piero


2 Answers

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)'

like image 110
zaph Avatar answered Nov 19 '25 04:11

zaph


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])];
like image 41
Gabriele Petronella Avatar answered Nov 19 '25 03:11

Gabriele Petronella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!