如何使用 NSRegularExpression 提取某些文本?
•浏览 1
How to extract certain text with NSRegularExpression?
我正在尝试从以下代码中提取 (80.4):
NSString *originalString; //which will contain"", however you want to get it there
NSString *afterColon = [[originalString componentsSeparatedByString:@":"] objectAtIndex:1];
float theValue = [afterColon floatValue];
width\\s*:\\s*(\\d+.\\d+)\\s*px
提取该文本的表达式是什么样的?谢谢。
对于这种特殊情况,正则表达式是相当重量级的。我会这样做:
NSString *originalString; //which will contain"", however you want to get it there
NSString *afterColon = [[originalString componentsSeparatedByString:@":"] objectAtIndex:1];
float theValue = [afterColon floatValue];
width\\s*:\\s*(\\d+.\\d+)\\s*px
这里有两种可能性,但答案会因以下因素而异:
1) 文本中还有哪些您不想匹配的其他内容,
2) 以及您允许匹配哪些变体(例如,在要匹配的测试中添加空格或换行,或交换要匹配的文本部分的顺序)
这仅匹配给定字符串的"width:80.4px"部分(允许额外的空白):
NSString *originalString; //which will contain"", however you want to get it there
NSString *afterColon = [[originalString componentsSeparatedByString:@":"] objectAtIndex:1];
float theValue = [afterColon floatValue];
width\\s*:\\s*(\\d+.\\d+)\\s*px
这匹配你给的整个字符串(也允许额外的空格):
NSString *originalString; //which will contain"", however you want to get it there
NSString *afterColon = [[originalString componentsSeparatedByString:@":"] objectAtIndex:1];
float theValue = [afterColon floatValue];
width\\s*:\\s*(\\d+.\\d+)\\s*px
所以在这些正则表达式中,80.4 将被捕获到 $1 捕获组中。