如何在 c++ 中regex_match #(哈希符号)

How to regex_match # (hash symbol) in c++?

本文关键字:哈希 符号 match c++ regex      更新时间:2023-10-16

我正在阅读.C 和 .C++中的 CPP 文件。目前使用 BOOST 进行recursive_directory迭代器。

我的问题是我尝试使用正则表达式来提取 C 文件中的 #define 变量。 但是正则表达式根本不匹配。如何regex_match(#define???

注意:正则表达式

只是标准::正则表达式,而不是 boost::正则表达式

代码片段:

            //input stream file
            ifstream inFile(path.string(),ios_base::in);
            //reading file line by line
            while(getline(inFile,readLine))
            {
                //Excluding comments
                if(regex_match(readLine,regex("\/|;|\*")))
                {
                    //ignore do nothing
                }
                else if(regex_match(readLine,regex("#")))
                {
                    cout<<"regex # matched"
                }
尝试regex_match(readLine,regex("#"), regex_match(readLine,regex("^#

"), regex_match(readLine,regex("^\#")--> # 不是特别的,但仍然只是想检查regex_match(readLine,regex(".#")

没有什么比这更好的..任何人都可以帮忙???

编辑:IM使用VS2012,视窗8

更新:".#."效果好...谢谢大家

在这里更新,以便像我这样有疑问的每个人都可以轻松查看它.. 谢谢

尝试正

则表达式模式

"#.*"

这种模式将匹配一个 #,后跟任意数量的字符,直到换行符,并且适用于我的所有测试用例(尽管很少),假设我答对了问题。

这是文档说:

The entire target sequence must match the regular expression for this function
 to return true (i.e., without any additional characters before or after the match).
 For a function that returns true when the match is only part of the sequence,
 see regex_search.

所以它应该是下面的一个与整个字符串匹配:

else if(regex_match(readLine,regex(".*#.*")))

或者,如果#在行首。

else if(regex_match(readLine,regex("^#.*")))