C#正则表达式优化

时间:2013-10-30 00:13:35

标签: c# regex performance url

我正在尝试解析文件中的网址。我的正则表达式在80%的时间内正在工作,但我需要修改它以用于异常。它开始变得复杂,我想知道如何为这个输入文件编写一个漂亮而干净的正则表达式,以便将主机放在一个组中,将URI部分放在一个组中。

Ex:http://stackoverflow.com/index.php其中stackoverflow.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的链接并添加一些其他修补程序并获得一个漂亮而干净的正则表达式?

1 个答案:

答案 0 :(得分:7)

正则表达式是一个非常灵活的工具,但对于任何类型的标准化格式,几乎总有一个标准的解析器可以更快更好地完成工作。

使用System.Uri(http://msdn.microsoft.com/en-us/library/system.uri.aspx),它将为您处理所有角落案例。