Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C Posix正则表达式捕获组匹配序列_C_Regex - Fatal编程技术网

C Posix正则表达式捕获组匹配序列

C Posix正则表达式捕获组匹配序列,c,regex,C,Regex,我在c程序中有以下文本字符串和正则表达式模式: char text[] = " identification division. "; char pattern[] = "^(.*)(identification *division)(.*)$"; 使用regexec()库函数,我得到了以下结果: String: identification division. Pattern: ^(.*)(identification *division)

我在c程序中有以下文本字符串和正则表达式模式:

char text[] = "        identification     division. "; 
char pattern[] = "^(.*)(identification *division)(.*)$"; 
使用regexec()库函数,我得到了以下结果:

String: identification division. Pattern: ^(.*)(identification *division)(.*)$ Total number of subexpressions: 3 OK, pattern has matched ... begin: 0, end: 37,match: identification division. subexpression 1 begin: 0, end: 8, match: subexpression 2 begin: 8, end: 35, match: identification division subexpression 3 begin: 35, end: 37, match: . 字符串:标识分区。 图案:^(.*)(标识*部门)(.*)$ 子表达式总数:3 好的,模式匹配了。。。 开始:0,结束:37,匹配:识别分区。 子表达式1开始:0,结束:8,匹配: 子表达式2开始:8,结束:35,匹配:标识除法 子表达式3开始:35,结束:37,匹配:。 我想知道,既然正则表达式引擎以贪婪的方式匹配,并且第一个捕获组(.*)匹配任意数量的字符(新行字符除外),为什么它不匹配文本字符串中的字符(直到“.”),而不是只匹配前8个空格

每个捕获组都必须匹配吗

是否有关于捕获组如何匹配文本字符串的规则


谢谢。

正如您所说的,如果贪婪的组(.*)消耗了整个字符串,则正则表达式的其余部分将没有任何匹配的内容,这将使您的正则表达式与字符串不匹配。因此,是的,每个捕获组(和其他模式部分)都需要匹配。这正是您在正则表达式中指定的内容

试试下面的字符串,用不情愿的和贪婪的第一组运行代码,你会看到区别

char text[] = "    identification  division    identification     division. ";

正则表达式尽可能贪婪,但又不太贪婪。如果左侧组像您预期的那样贪婪,那么与“identification division”匹配的组将无法匹配,错误地拒绝了
文本,这显然是在语言中;谁告诉你的?我明白你的意思。当我尝试您的文本字符串时,第一个捕获组(.*)与第二个“标识”之前的文本匹配。所以现在我很清楚,每个捕获组都需要匹配,除非它是可选的。如果我将模式更改为char pattern[]=“^(.*)(标识划分)?(.)$”;然后,第一个捕获组将匹配文本直至结束。谢谢