[英]c++ using iteration function for compiler
因此,我试图构建一个小型的词法扫描器,对文本进行标记化并确定每个标记的类型。 输出应该是一个文本文件,该文件具有令牌和令牌的行号,在每一行中键入。 如果令牌未被任何RE接受,则它应报告一个有意义的错误,显示该令牌的行号,该令牌和该错误。 我在C ++中使用了regexp库,现在我试图在下面的代码中隐含Iterator函数,但是我不知道如何在这里使用它。
#include <iostream>
#include <string>
#include <regex>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
ofstream myfile;
myfile.open("mytext1.txt");
myfile << " int 33.2 + bla 059 3 " << endl;
myfile << " void nn + fbla 09 3 " << endl;
myfile << " int float + bsla 09 3.2 " << endl;
myfile.close();
string s;
regex keywords("int|if|else|while|float|return|void|breack|for");
regex id("[[:alpha:]]+[[:d:]]*[[:alpha:]]*", regex_constants::icase);
regex integer("[[:d:]]+");
regex floatt("[[:d:]]+[.]+[[:d:]]+");
regex symbolls("[&&]|[||]|[<=]|[>=]|[==]|[<]|[>]|[!=]|[=]|[(]|[)]|[{]|[}]|[;]|[,]|[.]|[+]|[-]|[*]|[/]|[/*]|[*/]");
regex comment("//[[:w:]]*");
ifstream myfile2("mytext1.txt");
//int linenum= 1;
if (myfile2.is_open())
{
while (getline(myfile2, s, ' '))
{
cout << s << ",";
//cout <<linenum<< s << ",";
bool match = regex_match(s, floatt);
if (match) cout << "float number" << endl;
match = regex_match(s, integer);
if (match)cout << "integer number" << endl;
match = regex_match(s, keywords);
if (match){ cout << "keywords" << endl; goto a;
}
match = regex_match(s, id);
if (match)cout << "identifer" << endl;
a: match = regex_match(s, comment);
if (match)cout << "comment" << endl;
match = regex_match(s, symbolls);
if (match)cout << "symbolls" << endl;}
} myfile2.close();
system("pause");
return 0;
}
正则表达式符号并没有按照您的想象做。
问题:
- 作为文字的元字符需要转义。
-没有量词的字符类只能匹配一个字符。
-交替优先从左到右(例如a|aw
将只匹配a
我们)。
解决方法是将最长的aw|a
放在首位。
有用的提示:不必使用posix。
至于函数regex_match()
,在C ++中通常需要regex来匹配整行。
要查找子字符串,请使用regex_search()
。
通常,编写一个解析器是相当复杂的,因为必须依次解析每个字符。 在任何阶段,每个令牌都应将逻辑置于仅接受某些字符或其他令牌的状态。
无论如何,祝你好运。
下面是一些原始的正则表达式。
keywords "int|if|else|while|float|return|void|breack|for"
-----------
int
| if
| else
| while
| float
| return
| void
| breack
| for
id "[a-zA-Z]+[0-9]*[a-zA-Z]*"
-----------
[a-zA-Z]+ [0-9]* [a-zA-Z]*
integer "[0-9]+"
-----------
[0-9]+
floatt "[0-9]+[.]+[0-9]+"
-----------
[0-9]+ [.]+ [0-9]+
symbols "[&]{2}|[|]{2}|<=|>=|[=]{2}|!=|/\\*|\\*/|[<>(){};,.+*/=-]"
-----------
[&]{2}
| [|]{2}
| <=
| >=
| [=]{2}
| !=
| /\*
| \*/
| [<>(){};,.+*/=-]
comment
-----------
// [a-zA-Z0-9_]*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.