使用正则表达式从文件中删除行注释

remove line comment from file by using regex

本文关键字:删除行 注释 文件 正则表达式      更新时间:2023-10-16

我使用下面的模式从文件中删除注释行,并在Visual Studio Editor中继承它。但是,相同的模式不适用于C++正则表达式类。

std::regex pattern ("#.*n");
fullText =  std::regex_replace (fullText,pattern,"");

上面的代码是实现中非常简短的部分:您可以假设所有文本都一次读入fullText

实际结果必须从文件/字符串中删除所有注释行。可以忽略尾随注释。

示例文件.txt扩展名,具有以下文本:

# Initialization file..
# This file supports line comments, and does not support trailing comments.
# Text here is not case sensitive.
# White spaces are ignored in file processing. 
# Values are comma "," separated. 

Colmn,          Colmn,  
1,              0xFF,
2,              0xFF, 
3,              0xFF,
4,              0xFF,
5,              0xFF,

我假设所有行都必须用n完成,并且我尝试选择#n之间的所有文本。

提前感谢您的任何建议。

这里的重点是.与符合 ECMAScript 5 的正则表达式中的回车符不匹配,并且n模式与 CR 字符不匹配,而r匹配。

您可以通过在模式末尾使用[rn]*来解决此问题:

std::regex pattern{"#.*[rn]*"};