Finding date & time in NSString using Regex

百般思念 提交于 2020-01-03 04:47:10

问题


I want to do something similar to this question: regular expression in ruby for strings with multiple patterns

But I want to do it Objective-C. Basically I want extract date and time from a string with a date and time after the @ sign.

For example I have a string: Feed the Rabbits @12, I want to extract the date and time after the @, the problem is that the string can vary, for example it could @12:00, @04/02/12, @04/02/12 12:00, @04/02/12 12:00 or just @04/02/12. Heres my current code to extract numbers from the string (it doesn't detect "/" or ":" so if the string is @04/02/12 it will only extract @04 because it stops at "/").

I can also extract the @12:00 part out using this RegEx pattern @([0-9]+:[0-9][0-9]).

NSString *regEx = @"@(\\d+)";

NSString *dateString;
r = [inputString rangeOfString:regEx options:NSRegularExpressionSearch];
if (r.location != NSNotFound) 
{
    dateString = [NSString stringWithFormat:@"%@",[inputString substringWithRange:r]];
    return dateString;
} 
else 
{
    return @"";
}

回答1:


The regular expression "@(\d+)" finds an "@" followed by one or more digits (and captures only the digits). If you want it to find digits and slashes, dashes, colons, etc., you'll need to include those in the regular expression. If you want to look for specific patterns of numbers & punctuation, you'll need multiple subexpressions connected with an "or" (that is, a | character).

Anticipating all of the possible ways to express a date and/or time is hard work, especially if you want to support multiple locales. You might find it more feasible to have your regular expression capture anything & everything after the "@" (if you're not sure how to do this, the NSRegularExpression docs should be helpful). Then you can pass the string off to NSDateFormatter for parsing as a date.



来源:https://stackoverflow.com/questions/10557035/finding-date-time-in-nsstring-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!