Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#正则表达式优化_C#_Regex_Performance_Url - Fatal编程技术网

C#正则表达式优化

C#正则表达式优化,c#,regex,performance,url,C#,Regex,Performance,Url,我正在尝试解析文件中的URL。我的正则表达式80%的时间都在工作,但我需要修改它以防出现异常。它开始变得复杂起来,我想知道如何为这个输入文件编写一个漂亮干净的正则表达式,以便在一个组中获得主机,在第二个组中获得URI部分 例:http://stackoverflow.com/index.php其中stackoverflow.com是主机,/index.php是URI 输入文件: //cdn.sstatic.net/stackoverflow/img/favicon.ico //cdn.sstat

我正在尝试解析文件中的URL。我的正则表达式80%的时间都在工作,但我需要修改它以防出现异常。它开始变得复杂起来,我想知道如何为这个输入文件编写一个漂亮干净的正则表达式,以便在一个组中获得主机,在第二个组中获得URI部分

例:
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有两个组:
cdn.ssstatic.net
/stackoverflow/img/favicon.ico
2://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png有两个组:
cdn.ssstatic.net
/stackoverflow/img/apple-touch-icon.png
3:/opensearch.xml有两个组:
/opensearch.xml
4:/有两组:
/
5 : http://www.stackoverflow.com 有两组:
http:
//www.stackoverflow.com
6 : http://www.stackoverflow.com/ 有两组:
www.stackoverflow.com
/
7 : http://stackoverflow.com/ 有两组:
stackoverflow.com
/
8 : http://careers.stackoverflow.com 有两组:
http:
//careers.stackoverflow.com
7:fakedomain/index.php有两个组:
假域名
/index.php
8:fakedomain.com/index.php有两个组:
fakedomain.com
/index.php
9:fakedomain.com/有两个组:
fakedomain.com
/
10:/fakedomain.com/有两个组:
/fakedomain.com/
11:/index.html/有两个组:
/index.html/
12:index.html有两个组:
index.html
13:分为两组:
C#正则表达式测试仪:


那么,我如何删除
.ico
.png
的链接,并添加一些其他修复程序,同时获得一个漂亮干净的正则表达式呢?

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


使用System.Uri(),它将为您处理所有的紧急情况

我同意您的一般方法,但是在本例中,
System.Uri
是有缺陷的,需要一些努力才能破解它。考虑在URL内拥有<代码> %2F字符-你必须自己修复它。谢谢提示,但是我想自己编码。如果ASM能提高应用程序的速度,我不想用它编写代码。那么,如果正则表达式不是一种方法,那么应该采取什么方法呢?圣诞老人:是马车吗?还是需要确保输入通过众多的Uri类方法正确地被取消扫描?纳斯特:如果您想要一个正确的解析器来处理您遇到的任何uri,而不仅仅是您预期的uri,那么您需要使用System.uri。或者,您也可以使用创建自己的实现作为参考。