数字后修剪字符串

时间:2011-01-10 16:19:43

标签: c# string url

我需要调整我的代码,以便在数字后修剪网址。 例如,我希望删除List = 36后的所有内容。字母和特殊字符是唯一可以跟随列表编号的潜在字符。所以我只想在列表编号后面读取字母或特殊字符时修剪网址。谢谢。

在提交时捕获的当前网址的示例

https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx?List=36caab7e%2D2234%2D4981%2D8225%%2Easpx

https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx?List=36,http://portal.test/testabc/Lists/TEST/AllItems.aspx

我希望在提交时抓取:

https://portal.test.com/sites/test/testabc/Lists/RFC/DispFormSort.aspx?List=36

我目前捕获网址的方法代码:

    public static string GenerateShortUrl(SPList list, int itemId)
    {
        try
        {
            var item = list.GetItemById(itemId);
            var itemUrl = string.Empty;

            if (item.File == null)
                itemUrl = SPContext.Current.Web.Url + "/" + list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + item.ID;
            else
                itemUrl = SPContext.Current.Web.Url + "/" + item.Url;

            var generatedShortedUrl = GetShortUrl(itemUrl);

            return generatedShortedUrl;
        }
        catch (Exception ex)
        {
            Utilities.WriteError(ex.ToString());

            throw new SPException("An error occurred while attempting to shorten a URL.", ex);
        }
    }

     private static string GetShortUrl(string itemUrl)
        {
            var shortId = Utilities.GenerateHash(itemUrl);
            var shortenerUrl = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                    var farm = SPAdministrationWebApplication.Local;
                    using (var site = farm.Sites[0])
                    {
                        using (var web = site.RootWeb)
                        {
                            if (!web.Properties.ContainsKey("LiebrandUrlShortener"))
                                throw new SPException(SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,CannotFindUrl", "liebrandurlshortener", web.Language));

                            var urlList = web.Lists[SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,StorageName", "liebrandurlshortener", web.Language)];

                            var query = new SPQuery();
                            query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + shortId + "</Value></Eq></Where>";

                            var items = urlList.GetItems(query);
                            if (items.Count == 0)
                            {

                                var urlListItem = urlList.Items.Add();
                                urlListItem["Title"] = shortId;
                                urlListItem["RedirectTo"] = itemUrl;

                                web.AllowUnsafeUpdates = true;
                                urlListItem.Update();
                                web.AllowUnsafeUpdates = false;

                            }

                            shortenerUrl = web.Properties["LiebrandUrlShortener"];
                        }
                    }
            });

            return shortenerUrl + "/" + shortId;
        }

        public static string GenerateShortUrl(string longUrl)
        {
            return GetShortUrl(longUrl);
        }



    }
}

5 个答案:

答案 0 :(得分:9)

您可以使用Regex捕获所有内容,直到?List = [number]。

您可以使用此正则表达式:

Regex.Match(str, @"^.*\?List=\d+").Value

答案 1 :(得分:0)

 string url = "https://portal.test.com/sites/test/testabc/Lists/RFC/DispFormSort.aspx?List=36caab7e%2D2234%2D4981%2D8225%%2E.aspx";

 Regex regex = new Regex(@"^.*List=\d+");
 Match match = regex.Match(url);

 if (match.Success)
 {
    Console.WriteLine(match.Value);
 }

编辑:更改了代码,我认为他只需要提取数字。

答案 2 :(得分:0)

有时艰难的方式是最直接的方式。基于Regex的答案将返回不符合预期格式的URL的错误值。

    static void Main(string[] args)
    {
        string inputString = @"https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx?List=36caab7e%2D2234%2D4981%2D8225%%2Easpx";

        //TEST CASES:

        //string inputString = @"https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx?SomeParam=36caab7e%2D2234%2D4981%2D8225%%2Easpx";
        //should return null

        //string inputString = @"https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx?SomeParam=nih543&List=786yui";
        //should return https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx?786

        //string inputString = @"https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx?";
        //should return null

        //string inputString = @"https://portal.test/sites/test/testabc/Lists/TEST/DispFormSort.aspx";
        //should return null

        string result = GetShortenedListURL(inputString);

        Console.WriteLine(result);
        Console.ReadKey();
    }

    private static string GetShortenedListURL(string InputString)
    {
        //Split URL into address and parameter tokens
        var tokens = InputString.Split('?');
        if (tokens.Length > 1)
        {
            var urlParams = tokens[1].Split('&');
            const string listStarter = "LIST=";

            //Loop through parameters looking for one that begins with List
            foreach (var param in urlParams)
            {
                if (param.ToUpperInvariant().StartsWith(listStarter))
                {
                    //Found the right parameter, now look for a contiguous string of numbers
                    for (int numCounter = listStarter.Length; numCounter < param.Length; numCounter++)
                    {
                        if (!Char.IsDigit(param[numCounter]))
                        {
                            if (numCounter > listStarter.Length)
                            {
                                return tokens[0] + "?" + param.Substring(listStarter.Length, numCounter - listStarter.Length);
                            }
                        }
                    }

                }
            }

        }

        return null;
    }

答案 3 :(得分:0)

你绝对可以使用正则表达式来做到这一点。正如你所说,字母和特殊字符是唯一可以跟随列表编号的潜在字符,我的正则表达式正在拾取所有内容,直到?List = [number]以及任何字母和特殊字符,直到它找到一个不应该被选中的数字或字符达

Regex.Match(url, @"^.*\?List=\d+[A-Za-z._%+-]*+").Value

尝试在此处测试:http://www.regexplanet.com/simple/index.html

答案 4 :(得分:0)

我更喜欢LINQ:

string url = @"https://portal.test/...";
string flag = "List=";
int flagIndex = url.IndexOf(flag) + flag.Length;
string shortUrl = new string(url.TakeWhile((ch, index) => 
                          index < flagIndex || char.IsDigit(ch)).ToArray());