【问题标题】:Comparing a string with a regEx wildcard value将字符串与正则表达式通配符值进行比较
【发布时间】:2011-08-08 21:48:07
【问题描述】:

所以我需要根据 reg ex 通配符值列表检查一个字符串 (url) 以查看是否存在匹配项。我将拦截一个 HTTP 请求,并根据预先配置的值列表对其进行检查,如果有匹配项,则对 URL 执行一些操作。例子:

Request URL: http://www.stackoverflow.com

Wildcards: *.stackoverflow.com/
           *.stack*.com/
           www.stackoverflow.*

有没有什么好的 C++ 库可以做到这一点?任何好的例子都会很棒。我的伪代码看起来像:

std::string requestUrl = "http://www.stackoverflow.com";
std::vector<string> urlWildcards = ...;

BOOST_FOREACH(string wildcard, urlWildcards) {
    if (requestUrl matches wildcard) {
        // Do something
    } else {
        // Do nothing
    }
}

非常感谢。

【问题讨论】:

标签: c++ regex


【解决方案1】:

以下代码示例使用正则表达式来查找精确的子字符串匹配。搜索由静态 IsMatch 方法执行,该方法将两个字符串作为输入。第一个是要搜索的字符串,第二个是要搜索的模式。

#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;

int main()
{
    array<String^>^ sentence = 
        {
            "cow over the moon",
            "Betsy the Cow",
            "cowering in the corner",
            "no match here"
        };

    String^ matchStr = "cow";
    for (int i=0; i<sentence->Length; i++)
    {
        Console::Write( "{0,24}", sentence[i] );
        if ( Regex::IsMatch( sentence[i], matchStr,
                 RegexOptions::IgnoreCase ) )
            Console::WriteLine("  (match for '{0}' found)", matchStr);
        else
            Console::WriteLine("");
        }
        return 0;
    }
}

来自 MSDN (http://msdn.microsoft.com/en-us/library/zcwwszd7(v=vs.80).aspx) 的代码。

【讨论】:

  • 这是针对 C++/CLR 的。问题似乎要求原生 C++ 解决方案。
【解决方案2】:

如果你使用VS 2010,考虑使用c++ tr1引入的正则表达式。

更多详情请参考以下页面。

http://www.johndcook.com/cpp_regex.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多