我正在尝试包含一个包含不同变量的S表达式,并根据其类型对它们进行标记。我对regex还是很陌生,所以我不完全确定为什么它只匹配括号和变量类型的else条件。如果您知道为什么我的正则表达式与 token 不匹配,请告诉我!
#include <string>
#include <regex>
#include <iostream>
#define print(var) std::cout << var << std::endl
std::string INT_REGEX = "\b[0-9]{1,3}[0-9]{1,3}\b",
DOUBLE_REGEX = "\b[0-9]{1,3}.[0-9]{1,3}\b",
BOOLEAN_REGEX = "^(true|false)$";
bool matchRegex(std::string pattern, std::string inputString) {
std::regex expression(pattern);
return std::regex_match(inputString, expression);
}
void detectTokenType(std::string strToken) {
if (strToken == "(" | strToken == ")")
print("Parenthesis");
else if (matchRegex(INT_REGEX, strToken))
print("Integer");
else if (matchRegex(DOUBLE_REGEX, strToken))
print("Double");
else if (matchRegex(DOUBLE_REGEX, strToken))
print("Boolean");
else
print("Variable name or string");
}
void tokenize(std::string listData) {
std::vector<char> tokenBuffer;
for (int i = 0; i < listData.length(); i++) {
char currChar = listData[i];
if (i == listData.length() - 1) {
tokenBuffer.push_back(currChar);
std::string strToken(tokenBuffer.begin(), tokenBuffer.end());
detectTokenType(strToken);
}
else if (currChar != ' ') {
tokenBuffer.push_back(currChar);
}
else {
std::string strToken(tokenBuffer.begin(), tokenBuffer.end());
tokenBuffer.clear();
detectTokenType(strToken);
}
}
}
int main() {
std::string codeSnippet = "( 2 3.0 true )";
tokenize(codeSnippet);
return 0;
}
最佳答案
在您的正则表达式字符串中,您使用的不是单词边界的\b
。相反,您需要\\b
。同样,.
具有特殊含义(这是一个与任何字符匹配的通配符)。如果要匹配文字.
,则需要\\.
。
另外,您正在检查INT_REGEX
中是否有至少两位数字,这是不必要的:
std::string INT_REGEX = "\\b[0-9]{1,3}\\b",
DOUBLE_REGEX = "\\b[0-9]{1,3}\\.[0-9]{1,3}\\b",
BOOLEAN_REGEX = "^(true|false)$";
另外,您还需要检查DOUBLE_REGEX
中是否有Boolean
大小写,因此您需要对其进行修复。这是demo。
关于c++ - 为什么我的代码与这些s表达式不匹配正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63528446/