查找与正则表达式匹配的子字符串

Find matching substring to a regex

假设我有一个长字符串,它由所有匹配某些正则表达式的子字符串组成。

例如,我有 2 个正则表达式:

标识符:^[a-z]\S

运营商:^(:|;|*)

给定以下字符串:

a12vc+adh*v15

我想获取所有匹配项,例如:

While(hasNextRegex(str)) {
  printf("%s\n", nextRegex(str));
} 

将打印:

a12vc   (first match) 
+       (second match) 
adh     (third match) 
*       (fourth match) 
v15     (fifth match) 

我正在为正则表达式使用 slre 库。仅限C语言。

你对我的问题有什么想法吗?提前致谢!!

SLRE 一起分发的 README.md 中的文档包含一个使用单个 RE 进行迭代搜索的示例。您需要决定您需要使用的 RE 并应用该示例中显示的技术。

假定字符串 a12vc+adh*v15 将生成以下值:

  1. a12vc
  2. +
  3. adh
  4. *
  5. v15

您需要一个能够识别标识符(首字母、后续字母数字)和运算符(单个标点符号)的正则表达式。 SLRE 文档表明 SLRE 不支持 \w.

因此,标识符匹配(如果使用不区分大小写):

[a-z][a-z0-9]*

如果 desired/required.

,您可以在模式中添加下划线

运算符包括:

[*+-/;:]

因此,应该工作的正则表达式是:

([a-z][a-z0-9]*|[*+-/;:])

因此,示例中的代码可以改编为:

#include "slre.h"
#include <stdio.h>

int main(void)
{
    static const char str[] = "a12vc+adh*v15";
    static const char regex[] = "([a-z][a-z0-9]*|[*+-/;:])";
    struct slre_cap caps[1];
    int str_len = sizeof(str) - 1;
    const char *base = str;
    const char *end = str + sizeof(str);

    while (base < end)
    {
        int len = slre_match(regex, base, str_len, caps, 1, SLRE_IGNORE_CASE);
        if (len <= 0)
            break;
        printf("Found token: [%.*s]\n", caps[0].len, caps[0].ptr);
        base += len;
        str_len -= len;
    }
    return 0;
}

示例输出:

Found token: [a12vc]
Found token: [+]
Found token: [adh]
Found token: [*]
Found token: [v15]

这看起来像要求的。