ios - 在长字符串中修改时间格式正则表达式的发生

标签 ios regex xcode nsstring nsregularexpression

我的字符串包含时间值,例如08:30:00 AM和/或12:45:00 PM等。
现在我需要的是删除这些字符串中包含“seconds”值的部分,以使上面的字符串像08:30 AM和/或12:45 PM等。
我不能使用NSDateFormatter,因为该字符串不必始终在HH:MM:SS值中包含时间字符串。可能还有其他字符串值。这就是为什么我必须通过模式匹配来做到这一点。

我知道,我可以使用以下代码。但是我需要知道的是查找和修改字符串的正则表达式。

NSString *string = @"string containing 08:30:00AM values and some text";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"???" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0   range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", modifiedString);

提前致谢..

最佳答案

只是为了根据您自己的问题给出答案,此正则表达式模式将匹配您所追求的时间格式,并且括号将捕获小时和分钟部分,并允许您将其保留在修改后的字符串中:

NSString *timeText = @"This is a text with 08:30:23 and 9:23:54AM to test both formats.";

NSString *timePattern = @"([0-9]{1,2}:[0-9]{2}):[0-9]{2}";

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:timePattern
                                                                       options:0
                                                                         error:&error];

NSString *modifiedString = [regex stringByReplacingMatchesInString:timeText
                                                           options:0
                                                             range:NSMakeRange(0, timeText.length)
                                                      withTemplate:@"$1"];

结果是这样的:

这是带有08:30和9:23 AM的文本,可以测试两种格式。

替换字符串中的$n(其中n是数字)指的是正则表达式模式中的第n个捕获组(括号)-在这种情况下为小时,冒号和分钟。

就像您自己提到的那样,使用正则表达式可以直接在文本中进行替换,而无需进一步分析。

顺便说一句,此模式中没有字母,因此您不需要NSRegularExpressionCaseInsensitive

这个site是有用的,例如有关替换字符串和高级语法的讨论。

关于ios - 在长字符串中修改时间格式正则表达式的发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16278020/

相关文章:

ios - 有没有更好的方法来确定两个枚举值之间的距离?

ios - 设置AVCaptureDevice格式范围

java - 什么合适的正则表达式可以排除某个单词

ios - 图像不显示在设备中,而是显示在模拟器中

objective-c - 核心剧情: number of major x intervals

iOS 7 禁用向后滑动

Javascript/正则表达式 : Lookbehind Assertion is causing a "Invalid group" error

javascript - 用数字和特殊字符替换数字

ios - 编辑时tableView中没有didSelectRowAtIndexPath()

xcode - iOS 5屏幕初始自动旋转