我正在尝试使用正则表达式来匹配以下两种字符串类型:
Name(p0, p1,...pN)
和:
Name()
我目前正在使用正则表达式:
@"[a-z]+\([^()]+\)"
我能理解:
[a-z] = Match any character from a to z
我不太确定:
[^()] ?= Match any character between '(' and ')'
我相信它属于 group表示为:
\([^()]+\)
但我还是不确定。
目前该表达式适用于:
Name(p0, p1,...pN)
但是当括号之间没有逗号分隔字符时,我无法让它匹配。即:
Name()
为什么第二个表达式会失败?
编辑:
根据您的回答,我确定了以下几点(如有错误请指正):
+ = ONE or more times
* = ZERO or more times
[] = Groups characters to match or ignore
^ = Logical NOT
[a-z]+ = Match a lowercase letter (ONE or more times)
\( = Match the character '('
[^()]* = Match anything that's NOT '(' or ')' (ZERO or more times)
\) = Match the character ')'
请您参考如下方法:
[a-z]+ = Match any character from a to z, 1 or more times
\( = Match "(" literally
[^()]+ = Match anything that's NOT "(" or ")", 1 or more times
\) = Match ")" literally
如 Billy Moon 所说,在第三个“部分”中使用 * 而不是 + 来匹配“括号内的非括号”0 次或多次,而不是 1 次或多次。
括号不构成一个组 - 它们用“\”转义。
