正在检查的字符串类似于以下内容(注意括号之间的空格):
[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);