日期:2014-05-18  浏览次数:21044 次

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……