简体   繁体   中英

remove line comment from file by using regex

I used the pattern below to remove comment lines from file, and succeed it in Visual Studio Editor. However, the same pattern didn't work with C++ regex class.

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

Code above is a very brief part from the implementation: You can assume all text is read into fullText at once.

Actual results must remove all comment lines from file/string. Trailing comments can be ignored.

Sample file is.txt extension and has the text below:

# 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,

I assume all lines must be finished with \n , and I attempt to select all text between # and \n .

Thanks in advance for the any advice.

The point here is that . does not match carriage returns in the ECMAScript 5 compliant regex and \n pattern does not match CR chars while \r does.

You may fix the issue by using [\r\n]* at the end of the pattern:

std::regex pattern{"#.*[\r\n]*"};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM