我有一个正则表达式,我已经用 https://regexr.com/ 进行了测试,它工作正常的地方。但在 c 中它找不到任何匹配。
我的代码如下;我已经删除了所有不必要的内容。
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
int main ()
{
char * str = "<sql db=../serverTcp/Testing.db query=SELECT * From BuyMarsians;\>";
char * regex = "<sql\s+db=(.+)\s+query=(.+;)\s*\\>";
regex_t regexCompiled;
if (regcomp(®exCompiled,regex,REG_EXTENDED))
{
printf("Could not compile regular expression.\n");
fflush(stdout);
};
if (!regexec(®exCompiled,str, 0, NULL, 0)) {
printf("matched");
fflush(stdout);
}
regfree(®exCompiled);
return 0;
}
最佳答案
您需要转义反斜杠。改变
char * regex = "<sql\s+db=(.+)\s+query=(.+;)\s*\\>";
至
char * regex = "<sql\\s+db=(.+)\\s+query=(.+;)\\s*\\\\>";
请注意,这是极其低效的。更高效的正则表达式使用非贪婪量化,带有 ?
:
<sql\s+db=(.+?)\s+query=(.+;)\s*\\>
// ^ key change
那就变成:
char * regex = "<sql\\s+db=(.+?)\\s+query=(.+;)\\s*\\\\>";
另请注意:要匹配的字符串还包括 \
。你也需要在那里逃避它:
char * str = "<sql db=../serverTcp/Testing.db query=SELECT * From BuyMarsians;\\>";
关于c - 正则表达式在c中不匹配,但可以与在线解释器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653433/