我已经成功使用以下方法获取所有字母(至少是空格之前的):
@"^.*([A-Z][a-z].*)]\s"
然而,我希望匹配的是(
而非空格…我该怎么做?
不包含括号'('的匹配
(
字符,那么这应该可以工作:@"^.*?(?=\()"
@"^[a-zA-Z]*(?=\()"
解释:
^ Matches the beginning of the string
.*? One or more of any character. The trailing ? means 'non-greedy',
which means the minimum characters that match, rather than the maximum
(?= This means 'zero-width positive lookahead assertion'. That means that the
containing expression won't be included in the match.
\( Escapes the ( character (since it has special meaning in regular
expressions)
) Closes off the lookahead
[a-zA-Z]*? Zero or more of any character from a to z, or from A to Z
编辑: 实际上,如Casimir在他的答案中所指出的,使用.*?
可能比较麻烦,使用[^\)]*
可能更容易。在字符类(字符类是[...]
构造)中使用的^
反转了其含义,因此它不是“这些字符中的任何一个”,而是“除了这些字符之外的任何一个”。因此,使用该结构的表达式将是:
@"^[^\(]*(?=\()"
[a-zA-Z]*?
中的非贪婪量词没有起到任何有用的作用。与 .*
或 .*?
不同,[a-zA-Z]*
无法匹配 (
,因此您不需要偷偷摸摸地查找匹配项。 - Alan Moore[a-zA-Z]
无法匹配 (
,在实际使用中,该表达式并不是很有帮助,而第一个表达式更有意义。 - rossipedia使用限制字符类是最好的方法
@"^[^(]*"
[^(]
表示除了(
之外的所有字符。
请注意,您不需要捕获组,因为您想要的是整个模式。
您可以使用这个模式:
([A-Z][a-z][^(]*)\(
该组将匹配一个大写的拉丁字母,后跟一个小写的拉丁字母,后跟除开括号之外的任意数量的字符。请注意,^.*
不是必需的。
或者使用 非贪婪量词 来产生相同的基本行为:
([A-Z][a-z].*?)\(
^.*
开头是没有意义的;直接将其删除即可。 - Ry-[A-Z][a-z].*
并不像您想象的那样工作。 - JoeG