【发布时间】:2013-02-01 02:58:37
【问题描述】:
正在检查的字符串类似于以下内容(注意括号之间的空格):
[name] [address ] [ zip] [ phone number ]
我目前使用的表达方式...
\[([^\])]*)\]
...成功地捕获了括号内的每个文本,但它也捕获了前导和尾随空格,所以我最终得到:
"name" "address " " zip" " phone number "
但我寻求的是:
"name" "address" "zip" "phone number"
如何说服正则表达式不捕获这些示例中的空格? (除了嵌入的空格 - 例如“电话号码”中的单词之间的空格。)
(注意:我知道我可以从捕获的变量中修剪它在表达式完成后,但我试图在的上下文中进行表达式。)
感谢您的任何想法!下面是我用来测试的确切代码:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[([^\\])]*)\\]" options:0 error:nil];
NSString *string = @" [name] [address ] [ zip] [ phone number ] ";
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length])
withTemplate:@"\n\n[$1]"]; //note: adding brackets back here just to make it easy to see if the space has been trimmed properly from the captured value
NSLog(@"\n\n%@", modifiedString);
【问题讨论】:
标签: objective-c regex