objective-c - 过滤文本的正则表达式

标签 objective-c regex cocoa

在 Objective-C 中我有一个字符串如下:

CAST(407704969.734560,

我想提取数字:

407704969.734560

我正在使用的代码是这个:

NSString *stringToCheck = @"CAST(407704969.734560,"
NSRange   searchedRange = NSMakeRange(0, [stringToCheck length]);
NSString *pattern = @"(?<=CAST\\()(\\d+?.?\\d+?)(?=,)";
NSError  *error = nil;

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray* matches = [regex matchesInString:stringToCheck options:0 range: searchedRange];
for (NSTextCheckingResult* match in matches) {
    NSString* matchText = [stringToCheck substringWithRange:[match range]];
    NSLog(@"match: %@", matchText);
}   

我猜问题出在正则表达式中,我找不到任何关于它的教程。

最佳答案

您可以尝试使用以下正则表达式:

模式

CAST\((\d+?\.?\d+?),

输入

CAST(407704969.734560,

输出

Match 1: CAST(407704969.734560,
Group 1: 407704969.734560

或者,如果您只需要数字,请尝试以下操作:

模式

(?<=CAST\()(\d+?\.?\d+?)(?=,)

输入

CAST(407704969.734560,

输出

Match 1: 407704969.734560

这里有不长但非常好的正则表达式教程:

www.codeproject.com

关于objective-c - 过滤文本的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20336977/

相关文章:

objective-c - 如何在 macOS 游戏模板中挂接 NSWindowDelegate

ios - FBSession.activeSession.isOpen 返回 NO 即使用户已登录

objective-c - 关于在 ios View 之间共享信息

java - 为什么表达式 "[^\\w]+"不会生成与第一个字符相同的连续字符字符串?

php - JavaScript 中的 RegExp 在 PHP 中抛出错误

cocoa - NSTextView 和 NSAttributedString

ios - react-native iOS 原生模块 : calling method that activates network indicator asynchronously

iphone - 在不持有应用程序对象的情况下获取当前事件的 UIWindow/appDelegate 对象

mysql - 带有 ¶ 符号的 SQL 正则表达式

cocoa - 更新的 NSTableCellView.textField 未在表格显示中更新。