C中的正则表达式:例子?

Der*_*unk 163 c regex

我正在经历一些简单的例子和​​如何在ANSI C man regex.h中使用正则表达式的最佳实践并没有提供那么多的帮助.

Lau*_*ves 223

正则表达式实际上不是ANSI C的一部分.听起来你可能在谈论POSIX正则表达式库,它带有大多数(所有?)*nixes.这是在C中使用POSIX正则表达式的示例(基于):

#include <regex.h>        
regex_t regex;
int reti;
char msgbuf[100];

/* Compile regular expression */
reti = regcomp(&regex, "^a[[:alnum:]]", 0);
if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
    puts("Match");
}
else if (reti == REG_NOMATCH) {
    puts("No match");
}
else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
}

/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);
Run Code Online (Sandbox Code Playgroud)

或者,您可能需要查看PCRE,它是C中与Perl兼容的正则表达式的库.Perl语法几乎与Java,Python和许多其他语言中使用的语法相同.POSIX的语法是由所使用的语法grep,sed,vi等.

  • 除非你需要避免依赖我第二次PCRE,它有一些很好的语法增强,并且非常稳定.至少对于某些旧版本的Linux,"内置"正则表达式库不会因某些输入字符串和某些"几乎"匹配或涉及大量特殊字符的正则表达式而崩溃 (6认同)
  • @lixiang`regcomp`,`cflags`的最后一个参数是一个位掩码.来自http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html:"cflags参数是零或多个以下标志的按位包含OR ......".如果OR-在一起为零,你将得到0.我看到`regcomp`的Linux手册页说"cflags可能是按位 - 或者是下面的一个或多个",这看起来似乎有误导性. (2认同)
  • 您可以使用以下内容从匹配组中提取文本:`regmatch_tmatches[MAX_MATCHES]; if (regexec(&amp;exp, sz, MAX_MATCHES,matches, 0) == 0) { memcpy(buff, sz +matches[1].rm_so,matches[1].rm_eo -matches[1].rm_so); printf("group1: %s\n", buff); }` 注意组匹配从 1 开始,组 0 是整个字符串。为越界等添加错误检查。 (2认同)
  • 关于在`regcomp`失败后是否需要`regfree`,虽然它确实相当不明确,但这表明不应该这样做:https://www.redhat.com/archives/libvir-list/2013 - 9月/ msg00276.html (2认同)

Mic*_*ngh 12

它可能不是你想要的,但像re2c这样的工具可以将POSIX(-ish)正则表达式编译成ANSI C.它是作为替代编写的lex,但是这种方法可以让你牺牲最后一点速度的灵活性和易读性,如果你真的需要它.


die*_*pos 9

这是使用 REG_EXTENDED 的示例。这个正则表达式

"^(-)?([0-9]+)((,|.)([0-9]+))?\n$"
Run Code Online (Sandbox Code Playgroud)

允许您捕获西班牙系统和国际系统中的十进制数。:)

#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
regex_t regex;
int reti;
char msgbuf[100];

int main(int argc, char const *argv[])
{
    while(1){
        fgets( msgbuf, 100, stdin );
        reti = regcomp(&regex, "^(-)?([0-9]+)((,|.)([0-9]+))?\n$", REG_EXTENDED);
        if (reti) {
            fprintf(stderr, "Could not compile regex\n");
            exit(1);
        }

        /* Execute regular expression */
        printf("%s\n", msgbuf);
        reti = regexec(&regex, msgbuf, 0, NULL, 0);
        if (!reti) {
            puts("Match");
        }
        else if (reti == REG_NOMATCH) {
            puts("No match");
        }
        else {
            regerror(reti, &regex, msgbuf, sizeof(msgbuf));
            fprintf(stderr, "Regex match failed: %s\n", msgbuf);
            exit(1);
        }

        /* Free memory allocated to the pattern buffer by regcomp() */
        regfree(&regex);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 您不认为将“regcomp”保留在循环之外更好吗?除非每次使用时都应该初始化。 (3认同)

kia*_*uno 8

man regex.h报告regex.h没有手动输入,但man 3 regex 为您提供了一个页面,解释了用于模式匹配的POSIX函数.

GNU C库:正则表达式匹配中描述了相同的功能,其中解释了GNU C库既支持POSIX.2接口,也支持GNU C库多年来使用的接口.

例如,对于打印作为参数传递的哪些字符串匹配作为第一个参数传递的模式的假设程序,您可以使用类似于以下代码的代码:

#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_regerror (int errcode, size_t length, regex_t *compiled);

int
main (int argc, char *argv[])
{
  regex_t regex;
  int result;

  if (argc < 3)
    {
      // The number of passed arguments is lower than the number of
      // expected arguments.
      fputs ("Missing command line arguments\n", stderr);
      return EXIT_FAILURE;
    }

  result = regcomp (&regex, argv[1], REG_EXTENDED);
  if (result)
    {
      // Any value different from 0 means it was not possible to 
      // compile the regular expression, either for memory problems
      // or problems with the regular expression syntax.
      if (result == REG_ESPACE)
        fprintf (stderr, "%s\n", strerror(ENOMEM));
      else
        fputs ("Syntax error in the regular expression passed as first argument\n", stderr);
      return EXIT_FAILURE;               
    }
  for (int i = 2; i < argc; i++)
    {
      result = regexec (&regex, argv[i], 0, NULL, 0);
      if (!result)
        {
          printf ("'%s' matches the regular expression\n", argv[i]);
        }
      else if (result == REG_NOMATCH)
        {
          printf ("'%s' doesn't the regular expression\n", argv[i]);
        }
      else
        {
          // The function returned an error; print the string 
          // describing it.
          // Get the size of the buffer required for the error message.
          size_t length = regerror (result, &regex, NULL, 0);
          print_regerror (result, length, &regex);       
          return EXIT_FAILURE;
        }
    }

  /* Free the memory allocated from regcomp(). */
  regfree (&regex);
  return EXIT_SUCCESS;
}

void
print_regerror (int errcode, size_t length, regex_t *compiled)
{
  char buffer[length];
  (void) regerror (errcode, compiled, buffer, length);
  fprintf(stderr, "Regex match failed: %s\n", buffer);
}
Run Code Online (Sandbox Code Playgroud)

regcomp()至少需要的最后一个参数REG_EXTENDED,或者函数将使用基本正则表达式,这意味着(例如)您需要使用a\{3\}而不是a{3}使用扩展正则表达式,这可能是您期望使用的.

POSIX.2还有另一个用于通配符匹配的函数:fnmatch().它不允许编译正则表达式,或者获取与子表达式匹配的子字符串,但它特别适用于检查文件名何时匹配通配符(例如,它使用FNM_PATHNAME标志).


Qnd*_*del 5

虽然上面的答案很好,但我建议使用PCRE2。这意味着您可以立即使用所有正则表达式示例,而不必从某些古老的正则表达式进行翻译。

我已经对此做出了回答,但我认为它也可以在此提供帮助。

C中的正则表达式以搜索信用卡号

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}
Run Code Online (Sandbox Code Playgroud)

使用以下命令安装PCRE:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig
Run Code Online (Sandbox Code Playgroud)

使用编译:

gcc foo.c -lpcre2-8 -o foo
Run Code Online (Sandbox Code Playgroud)

检查我的答案以获取更多详细信息。