正则表达式在 C 中失败,在线测试通过 [英] Regex fails in C, online tests pass

查看:69
本文介绍了正则表达式在 C 中失败,在线测试通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 C 中使用它时应该工作的正则表达式失败.

A regex that should work fails when I use it in C.

当我在此处粘贴此正则表达式时 - https://regex101.com 并按预期测试它似乎没问题.

When I paste this regex here - https://regex101.com and test it it seems fine, as expected.

//clang 3.8.0

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

int main(void)
{
   char    *regPatt = regPatt = "^HR(\\d{2})$";
   regex_t  regex;
   short    retval = regcomp (&regex, regPatt, 0);
   short    status = regexec (&regex, "HR16", (size_t) 0, NULL, 0);

   printf ("%hd", status);

   regfree (&regex);
}

所以,在线测试工作正常.

So, online test work just fine.

正则表达式 - ^HR(\d{2})$

Regex - ^HR(\d{2})$

字符串 - HR16

例如在 https://regex101.com,一切都很好,我得到了匹配.

At https://regex101.com for example, all is fine, I get a match.

在我的代码中,它失败了.printf() 打印的值为 1 (REG_NOMATCH).

In my code, it fails. Value printed with printf() is 1 (REG_NOMATCH).

编辑 - 可以将代码粘贴到此处进行测试:https://rextester.com/l/c_online_compiler_gcc

edit - the code can be pasted for a test here: https://rextester.com/l/c_online_compiler_gcc

推荐答案

你应该使用 [0-9] 而不是 \d 并通过 REG_EXTENDEDregcomp 函数.

You should use [0-9] instead of \d and pass REG_EXTENDED to the regcomp function.

REG_EXTENDED
解释正则表达式时使用 POSIX 扩展正则表达式语法.如果未设置,则使用 POSIX 基本正则表达式语法.

REG_EXTENDED
Use POSIX Extended Regular Expression syntax when interpreting regex. If not set, POSIX Basic Regular Expression syntax is used.

这是更新代码:

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

int main(void)
{
   char    *regPatt = regPatt = "^HR([0-9]{2})$";
   regex_t  regex;
   short    retval = regcomp (&regex, regPatt, REG_EXTENDED);
   short    status = regexec (&regex, "HR16", (size_t) 0, NULL, 0);
   printf ("%hd", status);
   regfree (&regex);
}

这篇关于正则表达式在 C 中失败,在线测试通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆