3

一連の入力から正規表現を生成することは何とか可能ですか?

これが可能かどうかはわかりません。したがって、私はこの質問をここに投稿しています。

これを行うツールやウェブサイトはありますか?

さらに更新:次のような入力を入力するとします

どういうわけか、このタイプの入力を受け入れる正規表現を与える必要があります...これは可能ですか?

4

1 に答える 1

3

URL の例として、C# でまとめたものを次に示します。お役に立てると思います。

    //   Input "pattern" should consist of a string with ONLY the following tags:
    //   <protocol>  <web>  <website>  <DomainExtension>  <RestOfPath>
    //   Ex) GenerateRegexFor("<protocol><web><webite><domainextension>") will match http://www.google.com
    public string GenerateRegexFor(string pattern)
    {
        string regex = ProcessNextPart(pattern, "");
        return regex;
    }

    public string ProcessNextPart(string pattern, string regex)
    {
        pattern = pattern.ToLower();
        if (pattern.ToLower().StartsWith("<protocol>"))
        {
            regex += @"[a-zA-Z]+://";
            pattern = pattern.Replace("<protocol>", "");
        }
        else if (pattern.ToLower().StartsWith("<web>"))
        {
            regex += @"www\d?"; //\d? in case of www2
            pattern = pattern = pattern.Replace("<web>", "");
        }
        else if (pattern.ToLower().StartsWith("<website>"))
        {
            regex += @"([a-zA-Z0-9\-]*\.)+";
            pattern = pattern.Replace("<website>", "");
        }
        else if (pattern.ToLower().StartsWith("<domainextension>"))
        {
            regex += "[a-zA-Z]{2,}";
            pattern = pattern.Replace("<domainextension>", "");
        }
        else if (pattern.ToLower().StartsWith("<restofpath>"))
        {
            regex += @"(/[a-zA-Z0-9\-]*)*(\.[a-zA-Z]*/?)?";
            pattern = pattern.Replace("<restofpath>", "");
        }
        if (pattern.Length > 0 && pattern != "")
            return ProcessNextPart(pattern, regex);
        return regex;
    }

一致させたい URL のスタイルにもよりますが、これはほぼすべてのものに一致するはずです。URL に似ているが URL に似ていないテキストがある場合は、もう少しこだわりたいと思うかもしれません。

次のように使用します。

//to match something like "www.google.com/images/whatever"
//            \
//             \                 |www||.google.||----com------||/images/whatever
//              \                  |     |             |              |
//              \/                 V     V             V              V           
string regex = GenerateRegexFor("<web><website><domainextension><restofpath>");
 //to match something like "http://www.google.com/images/whatever"
string regex = GenerateRegexFor("<protocol><web><website><domainextension><restofpath>");

これらのタグは、任意の順序で使用できます (ただし、意味をなさないものもあります)。これも自由に構築してください。任意の数のパターンを表すために、必要な数のタグを追加できます。

ああ、仕事で何かをしてくれたことに対して+1。

于 2012-09-14T18:32:25.813 に答える