读书人

C#正则截取Url中的字符串解决办法

发布时间: 2012-08-08 14:32:45 作者: rapoo

C#正则截取Url中的字符串
Url中的字符串

string str1 = http://localhost:80/service.svc/Units
string str2 = http://localhost:80/service.svc/Units(1)
string str3 = http://localhost:80/service.svc/Units(1)/Location
string str4 = http://localhost:80/service.svc/Units(1)?$expand=Location
string str5 = http://localhost:80/service.svc/Units?$expand=Location

一“/”开始到“空”或“(”或“?”结尾的字符。

取出Url中的 Units 字符串。

求正则写法。


[解决办法]

C# code
string reg=@"/?(\w+)[(|?]*.*";
[解决办法]
C# code
            string tempStr = File.ReadAllText(@"C:\Users\M\Desktop\Test.txt", Encoding.GetEncoding("GB2312"));            string pattern = @"(?<=http://([^/(]*/)+)[^\s(?/]+(?=[(?\s])";            foreach (Match m in Regex.Matches(tempStr, pattern))            {                string result = m.Value;//循环输出 Units            }
[解决办法]
C# code
 List<string> list = new List<string>() {                "/Units",                "/Units(1)",                "/Units(1)/Location",                "/Units(1)?$expand=Location",                 "/Units?$expand=Location"            };            string pattern = @"(?<=/)[^\s(?/]+(?=(?>(?([(?/]).+|$)))";            string[] array = list.Select(a=>Regex.Match(a,pattern).Value).ToArray();            /*             *         [0]    "Units"    string                    [1]    "Units"    string                    [2]    "Units"    string                    [3]    "Units"    string                    [4]    "Units"    string             */
[解决办法]
"/\.svc\/(.*)/"
可以吗?
[解决办法]
探讨

引用:
C# code
List<string> list = new List<string>() {
"/Units",
"/Units(1)",
"/Units(1)/Location",
"/Units(1)?$expand=Location",
……


多谢,Return_false

我要截取的Url地址是一个,只是有五种情况。

[解决办法]
探讨
Url中的字符串

string str1 = http://localhost:80/service.svc/Units
string str2 = http://localhost:80/service.svc/Units(1)
string str3 = http://localhost:80/service.svc/Units(1)/Location
string str……

读书人网 >C#

热点推荐