[英]Regex for contents of parentheses
I'm trying to learn Regular Expressions but I can't understand how to set this one up correctly as an NSRegularExpression. 我正在尝试学习正则表达式,但无法理解如何将其正确设置为NSRegularExpression。 I need to get the contents of any parentheses in a string.
我需要获取字符串中任何括号的内容。
So: Belmont (O'Hare Branch) (Forest Pk-bound) 因此:Belmont(奥黑尔分公司)(森林Pk站)
would give me: 'O'Hare Branch' and 'Forest Pk-bound' 会给我:“ O'Hare分支”和“ Forest Pk-bound”
I would really appreciate a commented example. 我真的很感激一个示例。
Thank you! 谢谢!
\\(.*?\\)
will give you everything in between brackets. \\(.*?\\)
将为您提供括号之间的所有内容。 Sorry but I have no clue how to do it in a NSRegularExpression. 抱歉,但是我不知道如何在NSRegularExpression中进行操作。 You either have to wait for a IOS dev to come along or figure it our for yourself.
您要么必须等待IOS开发人员来临,要么自己解决它。
\( #escaped opening bracket
. #match anything
* #match . 0 - unlimited times
? #make the * not greedy
\) #escaped closing bracket
@"\\(.*?\\)"
Will do the work. 会做的工作。
Notice: That won't support nested parentheses like this: 注意:这将不支持像这样的嵌套括号:
Hi duck (debug duck (now just a regular duck))
So, the whole solution will be: 因此,整个解决方案将是:
NSString *string = @"Hi duck (debug duck), let's go to shower!";
NSRange range = NSMakeRange(0, [string length]);
NSString *pattern = @"\\(.*?\\)";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:range];
NSLog(@"%@", [string substringWithRange:[match rangeAtIndex:0]]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.