c++ - 为什么我的代码与这些s表达式不匹配正则表达式?

标签 c++ regex token tokenize regex-group

我正在尝试包含一个包含不同变量的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/

相关文章:

python - 使用正则表达式与文本中存在的模式进行字符串分割

c++ - 如何用字符串做随机数组?

c++ - 当构建有错误时,Eclipse C++ 从不运行

C++ 将字符串(或 char*)转换为 wstring(或 wchar_t*)

C++ mpz_class 和二进制文件

javascript - Reactjs map 返回意外标记}

python - pandas str.replace - 如果正则表达式在将字符串转换为数字时未能避免 NaN,则保留当前值

javascript - Chrome 句柄是否正确匹配?

java - 使用分隔符进行标记

iOS 4.0 Twitter 集成