首页 > 解决方案 > C regexec 找不到与简单贪婪正则表达式的最长匹配

问题描述

我正在尝试m*匹配immunity. 我阅读了 POSIXregex.h手册页并写了以下内容:

#include <stdio.h>
#include <regex.h>

#define DIE(condition, msg) do { \
  if (condition) { \
    puts(msg); \
    return 1; \
  } \
} while (0)

int main(void) {
  regex_t preg;
  regmatch_t match;
  DIE (regcomp(&preg, "m*", REG_EXTENDED), "Failed to compile regex.");
  DIE (regexec(&preg, "immunity", 1, &match, 0), "No regex match found");
  printf("Match starts at %d and ends at %d.", match.rm_so, match.rm_eo);
  return 0;
}

regexec报告匹配(返回 0),但rm_sorm_eo都等于 0。虽然这一个匹配(开头是一个空字符串),但手册页暗示总是首先返回最长的匹配,在这种情况下 1 和 3应该退回。当我将正则表达式更改为m+按预期工作时(1、3,而不是 1、2,这意味着它是贪婪的)。这里发生了什么?

标签: cregexposixglibcregex-greedy

解决方案


推荐阅读