2

誰かが私を助けてくれるかどうか疑問に思っていました。正規表現の例を探していましたが、それでも頭を悩ませることはできません。

文字列は次のようになります。

「ユーザーJaneDoe、IP:12.34.56.78」

「ユーザーJohnDoe、IP:34.56.78.90」

上記の文字列に一致する式を作成するにはどうすればよいですか?

4

2 に答える 2

4

問題は、これらをどの程度正確に一致させ、他に何を除外するかです。

入力文字列を単純.*.

これらをより正確に一致させる (そして、ユーザー名や IP などを抽出する可能性を追加する) には、次のようなものを使用できます"User ([^,]*), IP: (\\d{1,3}(\\.\\d{1,3}){3})"。入力内容によっては、コンマを含む名前 (例: "John James, Jr.") で問題が発生する場合がありますそれを許容しなければならない場合、急いでかなり醜くなります。

編集: 上記の正規表現をテスト/デモするためのコードを少し示します。現時点では、これは C++0x 正規表現クラスを使用しています。Boost を使用するには、名前空間を少し変更する必要があります (しかし、それで十分だと思います)。

#include <regex>
#include <iostream>

void show_match(std::string const &s, std::regex const &r) { 
    std::smatch match;
    if (std::regex_search(s, match, r))
        std::cout << "User Name: \"" << match[1] 
                  << "\", IP Address: \"" << match[2] << "\"\n";
    else
        std::cerr << s << "did not match\n";
}

int main(){ 

    std::string inputs[] = {
        std::string("User JaneDoe, IP: 12.34.56.78"),
        std::string("User JohnDoe, IP: 34.56.78.90")
    };

    std::regex pattern("User ([^,]*), IP: (\\d{1,3}(\\.\\d{1,3}){3})");

    for (int i=0; i<2; i++)
        show_match(inputs[i], pattern);
    return 0;
}

これにより、ユーザー名と IP アドレスが出力されますが、文字列全体を渡すだけでなく、個々の部分を一致させて出力していることを明確にするのに (ほとんど) 異なる形式ではありません。

于 2011-02-22T04:47:34.010 に答える
3
#include <string> 
#include <iostream>
#include <boost/regex.hpp>

int main() {

    std::string text = "User JohnDoe, IP: 121.1.55.86";
    boost::regex expr ("User ([^,]*), IP: (\\d{1,3}(\\.\\d{1,3}){3})");

    boost::smatch matches;

    try
    {
        if (boost::regex_match(text, matches, expr)) {

            std::cout << matches.size() << std::endl;

            for (int i = 1; i < matches.size(); i++) {
                std::string match (matches[i].first, matches[i].second);
                std::cout << "matches[" << i << "] = " << match << std::endl;
            }

        }
        else {
            std::cout << "\"" << expr << "\" does not match \"" << text << "\". matches size(" << matches.size() << ")" << std::endl;
        }
    } 
    catch (boost::regex_error& e)
    {
        std::cout << "Error: " << e.what() << std::endl;
    }

    return 0;
}

編集:文字列に欠落しているコンマを修正し、Davkaが指摘し、cmatchをsmatchに変更しました

于 2011-02-22T06:40:15.377 に答える