首页 > 解决方案 > 使用正则表达式将包含通配符“*”的字符串与一组字符串进行比较

问题描述

我有一组标准的字符串文字,如下所示:

actions = "GetClass ModifyClass DeleteClass ListObjects"

现在,当我给出输入字符串“GetClass”时,我的输出应该是“GetClass”。

如果我输入“Get*”,我的输出应该是“GetClass”。

如果我输入“*Class”,我的输出应该是一个包含“GetClass”、“ModifyClass”和“DeleteClass”的列表。

如果输入字符串是“*Objects”,我的输出应该只是“ListObjects”。

像 'Get','Class','Obj' 这样的输入不应该给出四个字符串文字中的任何一个,因为它们没有完全指定它们。

如何使用匹配、比较等正则表达式函数来获得此结果。请帮忙。请注意,我的代码使用的是 c++。

我曾尝试这样做:

boost::regex re("^"+input+"$");
while (boost::regex_search(actions, match, re) {
    //Push 'match' into the output list
    actions = match.suffix().str()

请提出更正建议。谢谢。

评论中建议的更改后我的代码如下所示

std::string wildcard("*");
std::osstringstream strStream;
for (int i=0; i<input.length(); i++) {
    if (input.compare(i, 1, wildcard) {
        strStream << "\\S";
    }
    strStream << wildcard
}
boost::regex re(strStream.str());
while (boost::regex_search(actions, match, re) {
    //Push 'match' into the output list
    actions = match.suffix().str()
}

标签: c++regex

解决方案


推荐阅读