Get substring of string by searching the string for the substring text?
How would you go about getting the substring of a string by passing the string the substring text that you are looking for. Also would you be able to combine regex with regular text wi开发者_StackOverflow社区thout causing any issues
If you want to know if a substring exists within a string you can use Contains. If you want to know the position of a substring within a string you can use IndexOf (which can also be used to see if it exists... see examples below).
Examples for checking existence of substring:
bool subStringExists = yourStringVariable.Contains("yourSubString");
bool subStringExists = yourStringVariable.IndexOf("yourSubString") >= 0;
Examples for finding position of substring:
int subStringPosition = yourStringVariable.IndexOf("yourSubString");
UPDATE:
Based on your comment about the URL matching, you can do it all with a regex expression. With regular expressions, you can have certain parts of the expression be literal, while other parts are variable. In the case of what you're trying to do you would have something like this for your regex:
// Will match on http://www.mywebsite.com/abc#.aspx, where # is 1 or more digits
const string regExCommand = "(http://www.mywebsite.com/abc\\d+\\.aspx)";
Here is a complete working example you can copy into a console project and play around with to find out exactly what you need:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace RegExExample
{
public class Program
{
static void Main()
{
var urls = new List<Url>
{
new Url
{
Name = "Match 1",
Address = "http://www.mywebsite.com/abc123.aspx"
},
new Url
{
Name = "Match 2",
Address = "http://www.mywebsite.com/abc45.aspx"
},
new Url
{
Name = "Match 3",
Address = "http://www.mywebsite.com/abc5678.aspx"
},
new Url
{
Name = "No Match 1",
Address = "http://www.otherwebsite.com/abc123.aspx"
// No match because otherwebsite.com
},
new Url
{
Name = "No Match 2",
Address = "http://www.mywebsite.com/def123.aspx"
// No match because def
}
};
// Will match on http://www.mywebsite.com/abc#.aspx, where # is 1 or more digits
const string regExCommand = "(http://www.mywebsite.com/abc\\d+\\.aspx)";
var r = new Regex(regExCommand, RegexOptions.IgnoreCase | RegexOptions.Singleline);
urls.ForEach(u =>
{
var m = r.Match(u.Address);
if (m.Success)
{
Console.WriteLine(String.Format("Name: {0}{1}Address: {2}{1}",
u.Name,
Environment.NewLine,
u.Address));
}
});
Console.ReadLine();
}
}
internal class Url
{
public string Name { get; set; }
public string Address { get; set; }
}
}
The output would be as follows:
Name: Match 1
Address: http://www.mywebsite.com/abc123.aspx
Name: Match 2
Address: http://www.mywebsite.com/abc45.aspx
Name: Match 3
Address: http://www.mywebsite.com/abc.5678.aspx
Since you are already know the substring, I assume you are checking to see if the string contains the substring; you can do
bool hasSubstring = str.Contains(subStr);
精彩评论