2

ファイルから URL を解析しようとしています。私の正規表現は 80% の確率で機能していますが、例外のために変更する必要があります。複雑になり始めており、この入力ファイルの 1 つのグループでホストを取得し、URI 部分を 1 秒で取得するための適切でクリーンな正規表現を作成する方法を知りたいと思います。

例:http://stackoverflow.com/index.phpstackoverflow.comホスト、/index.phpは URI です。

入力ファイル :

//cdn.sstatic.net/stackoverflow/img/favicon.ico
//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png
/opensearch.xml
/
#
http://www.stackoverflow.com
http://www.stackoverflow.com/
http://stackoverflow.com/
http://careers.stackoverflow.com
aaa#aaa.com
aaa.com#aaa
aaa#aaa
#aaa
#
fakedomain/index.php
fakedomain.com/index.php
fakedomain.com/
/fakedomain.com/
/index.html/
index.html

正規表現:

(?:.*?//)?(.*?)(/.*|$)

結果 :

1 : //cdn.sstatic.net/stackoverflow/img/favicon.ico has 2 groups:
    cdn.sstatic.net
    /stackoverflow/img/favicon.ico

2 : //cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png has 2 groups:
    cdn.sstatic.net
    /stackoverflow/img/apple-touch-icon.png

3 : /opensearch.xml has 2 groups:
    /opensearch.xml

4 : / has 2 groups:

    /

5 : http://www.stackoverflow.com has 2 groups:
    http:
    //www.stackoverflow.com

6 : http://www.stackoverflow.com/ has 2 groups:
    www.stackoverflow.com
    /

7 : http://stackoverflow.com/ has 2 groups:
    stackoverflow.com
    /

8 : http://careers.stackoverflow.com has 2 groups:
    http:
    //careers.stackoverflow.com

7 : fakedomain/index.php has 2 groups:
    fakedomain
    /index.php

8 : fakedomain.com/index.php has 2 groups:
    fakedomain.com
    /index.php

9 : fakedomain.com/ has 2 groups:
    fakedomain.com
    /

10 : /fakedomain.com/ has 2 groups:

     /fakedomain.com/

11 : /index.html/ has 2 groups:

     /index.html/

12 : index.html has 2 groups:
     index.html

13 :  has 2 groups:

C# 正規表現テスター: http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

では、リンクを削除し.icoたり.png、他の修正を追加したり、きれいできれいな正規表現を取得したりするにはどうすればよいでしょうか?

4

1 に答える 1

7

正規表現は非常に柔軟なツールですが、どのような種類の標準化された形式でも、ほとんどの場合、より高速で優れた作業を行う標準パーサーが存在します。

すべてのコーナー ケースを処理する System.Uri ( http://msdn.microsoft.com/en-us/library/system.uri.aspx ) を使用します。

于 2013-10-30T00:19:01.263 に答える