CS-603 (COMPILER DESIGN)
ABCA Activity -1
(Code Implementation)
Code: -
#include <iostream>
#include <regex>
#include <string>
#include <vector>
using namespace std;
void lexicalAnalyzer(const string &code) {
regex keyword("(int|void|return)");
regex identifier("[a-zA-Z_][a-zA-Z0-9_]*");
regex number("\\b\\d+\\b");
regex operators("[-+*/=]");
regex punctuation("[{}();]");
cout << "Lexical Analysis Output:\n";
sregex_iterator iter([Link](), [Link](), keyword);
sregex_iterator end;
while (iter != end) {
cout << "Keyword: " << iter->str() << endl;
iter++;
}
iter = sregex_iterator([Link](), [Link](), identifier);
while (iter != end) {
cout << "Identifier: " << iter->str() << endl;
iter++;
}
iter = sregex_iterator([Link](), [Link](), number);
while (iter != end) {
cout << "Number: " << iter->str() << endl;
iter++;
}
iter = sregex_iterator([Link](), [Link](), operators);
while (iter != end) {
cout << "Operator: " << iter->str() << endl;
iter++;
}
iter = sregex_iterator([Link](), [Link](), punctuation);
while (iter != end) {
cout << "Punctuation: " << iter->str() << endl;
iter++;
}
}
int main() {
string code = "void main() { int x=55, y=8, z; z=x-y; }";
lexicalAnalyzer(code);
return 0;
}
Output: -
Keyword: void
Keyword: int
Identifier: main
Identifier: x
Identifier: y
Identifier: z
Number: 55
Number: 8
Operator: =
Operator: -
Punctuation: {
Punctuation: ;
Punctuation: }
Submitted By: -
Shourya Prajapati
CS – D (B1)
0905CS221193