简体   繁体   中英

String operation in C#

I have an input string which data is coming in the following format:

  • "http://testing/site/name/lists/tasks"
  • "http://testing/site/name1/lists/tasks"
  • "http://testing/site/name2/lists/tasks" etc.,

How can I extract only name, name1, name2, etc. from this string?

Here is what I have tried:

SiteName = (Url.Substring("http://testing/site/".Length)).Substring(Url.Length-12) 

It is throwing an exception stating StartIndex cannot be greater than the number of characters in the string. What is wrong with my expression? How can I fix it? Thanks.

A better option will be to use Regex matching/replace

But the following will also work based on the assumption that all the urls will be similar in pattern

var value = Url.Replace(@"http://testing/site/", "").Replace(@"/lists/tasks", "");

The other option will be to use Uri

var uriAddress = new Uri(@"http://testing/site/name/lists/tasks");

then breaking down uri parts according to your requirement

This is a job for regexp:

string strRegex = @"http://testing/site/(.+)/lists/tasks";
RegexOptions myRegexOptions = RegexOptions.IgnoreCase;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"http://testing/site/name/lists/tasks" + "\r\n" + @"http://testing/site/name1/lists/tasks" + "\r\n" + @"http://testing/site/name2/lists/tasks" + "\r\n" + @"http://testing/site/name3/lists/tasks";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here. Reference to first group
  }
}

You could also use the Uri class to get the desired part:

string[] urlString = urlText.Split();
Uri uri = default(Uri);
List<string> names = urlString
    .Where(u => Uri.TryCreate(u, UriKind.Absolute, out uri))
    .Select(u => uri.Segments.FirstOrDefault(s => s.StartsWith("name", StringComparison.OrdinalIgnoreCase)))
    .ToList();

Assuming that the part always start with "name".

Because the Substring function with a single argument takes the index of the starting charachter and consume all to the end of the string. It will be a little naive, but you can start at charachter 19 : Url.Substring(19);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM