首页 > 解决方案 > c++ 正则表达式没有按预期工作(regex_search)

问题描述

我目前正在研究 c++ 中的正则表达式,我试图在字符串中搜索子字符串。

问题 :

细绳 :

<Directory />
AllowOverride none
Require all denied
</Directory>

<Directory "C:/xampp/htdocs/dashboard">
Options +Indexes
AllowOverride None
Require all granted
</Directory>

在这我只需要第一个目录内容,即

<Directory />
AllowOverride none
Require all denied
</Directory>

因此我使用了正则表达式

Regex : < *Directory *\/? *>(\n.*?)+<\/Directory>

在这个正则表达式中,我使用了\n.*? 这样它将返回第一个结果(惰性)。当我在https://regexr.com中尝试时它工作正常,但是当我使用 regex_search 时它显示不匹配。这怎么可能?我错过了什么吗?

代码 :

LPSTR logLocation = "C:\\xampp\\apache\\conf\\httpd.conf";

string logBuffer = RemoveCommentsFromFile(logLocation);

//cout<<logBuffer;

smatch match;
regex regx("< *Directory *\/? *>(\n.*?)+<\/Directory>");

if(regex_search(logBuffer,match,regx))
    cout<<match.str();

该代码基本上从文件中删除注释并将其作为字符串返回。

标签: c++regexc++11

解决方案


经过数小时的浪费时间,我终于找到了适合的解决方案。有两个正则表达式适合此解决方案。

Solution 1 : < *Directory */? *>(\\n|.*)+?</Directory>

我用了| (OR) 在捕获组中使用惰性 (?) 运算符停止第一个匹配项。但是,我在问题中发布的正则表达式似乎在所有正则表达式测试人员中都运行良好。

Solution 2 : < *Directory */? *>(\\s|\\S)+?</Directory>

只需将换行符和任何字符 (.) 替换为 \s 和 \S。

但是,已知 (\s|\S) 与 [\s\S] 相同,但看起来捕获组有效,但第二个无效。

我不知道它是怎么发生的!


推荐阅读