重复应用正则表达式
我有这样的文本表达式:
HIUPA:bla1bla1'HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'
我想提取以下文本片段:
HIUPD:bla2bla2'
我的 Objective-C 代码如下
HIUPD:bla3bla3'
所示:
-(void) ermittleKonten:(NSString*) bankNachricht
{
NSRegularExpression* regexp;
NSTextCheckingResult* tcr;
regexp = [NSRegularExpression regularExpressionWithPattern:@"HIUPD.*'" options:0 error:nil];
int numAccounts = [regexp numberOfMatchesInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])];
for( int i = 0; i < numAccounts; ++i ) {
tcr = [regexp firstMatchInString:bankNachricht options:0 range:NSMakeRange( 0, [bankNachricht length] )];
NSString* HIUPD = [bankNachricht substringWithRange:tcr.range];
NSLog(@"Found text is:\n%@", HIUPD);
}
}
在 Objective-C 代码中 numAccounts 是 1,但应该是 2。 字符串是发现是“HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'”
我用在线工具测试了正则表达式模式(http://www.regexplanet.com/simple/index.html )。在在线工具中,它运行良好,并提供了我想要的 2 个结果。
但我希望在 ios 代码中得到相同的结果,即“HIUPD:bla2bla2'”和“HIUPD:bla3bla3'”。模式有什么问题?
I've got text expressions like this:
HIUPA:bla1bla1'HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'
I want to extract the following text pieces:
HIUPD:bla2bla2'
And
HIUPD:bla3bla3'
My Objective-C code for this looks like this:
-(void) ermittleKonten:(NSString*) bankNachricht
{
NSRegularExpression* regexp;
NSTextCheckingResult* tcr;
regexp = [NSRegularExpression regularExpressionWithPattern:@"HIUPD.*'" options:0 error:nil];
int numAccounts = [regexp numberOfMatchesInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])];
for( int i = 0; i < numAccounts; ++i ) {
tcr = [regexp firstMatchInString:bankNachricht options:0 range:NSMakeRange( 0, [bankNachricht length] )];
NSString* HIUPD = [bankNachricht substringWithRange:tcr.range];
NSLog(@"Found text is:\n%@", HIUPD);
}
}
In the Objective-C code numAccounts is 1, but should be 2. And the string that is found is "HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'"
I tested the regular expression pattern with an online tool ( http://www.regexplanet.com/simple/index.html ). In the online tool it works fine and delivers 2 results as I want it to be.
But I would like to have the same result in the ios code, i.e. "HIUPD:bla2bla2'" and "HIUPD:bla3bla3'". What is wrong with the pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在与
.*
进行贪婪匹配,因此正则表达式会在.*
中捕获尽可能多的内容。您应该执行.*?
或[^']*
,以便*
无法匹配'< /代码>。
You're doing greedy matching with the
.*
, so the regular expression catches as much as it can in the.*
. You should be doing.*?
, or[^']*
, so that the*
can't match a'
.