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

标签 c regex substring

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

例如,我有 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]*

如果需要,您可以向模式添加下划线。

运算符包括:

[*+-/;:]

因此,应该有效的正则表达式是:

([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]

这看起来像所要求的。

关于c - 查找与正则表达式匹配的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552358/

相关文章:

c++ - 用于检查 MySQL 连接性和 InnoDB 插件的 C/C++ 程序

java - Android:将字符串读取到特定字符

python - python 检查一个字符串是否包含另一个字符串中相同顺序的所有单词?

swift - '子字符串(到 : )' is deprecated: Please use String slicing subscript with a ' partial range upto' operator

string - 如何找到包含给定字符串中所有字符的最小子字符串?

c - 文件中此时函数 ' ' 的参数过多

c - 向量化具有间接访问的循环

c - 理解c中两个链表实现之间的区别

javascript - 如何在不删除“的情况下替换以下^?

java - 使用 Positive Lookbehind 出现意外的正则表达式行为