質問

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 @"";
}
役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top