如何通过向字符串传递您要查找的子字符串文本来获取字符串的子字符串。另外,您是否能够将正则表达式与常规文本结合起来,而不会引起任何问题
最佳答案
如果您想知道字符串中是否存在子字符串,可以使用 Contains 。如果您想知道字符串中子字符串的位置,可以使用 IndexOf (也可以用来查看它是否存在......请参阅下面的示例)。
检查子字符串是否存在的示例:
bool subStringExists = yourStringVariable.Contains("yourSubString");
bool subStringExists = yourStringVariable.IndexOf("yourSubString") >= 0;
查找子字符串位置的示例:
int subStringPosition = yourStringVariable.IndexOf("yourSubString");
更新:
根据您对 URL 匹配的评论,您可以使用正则表达式来完成这一切。使用正则表达式,您可以让表达式的某些部分是文字,而其他部分是可变的。在您尝试执行的操作的情况下,您的正则表达式将具有以下内容:
// 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)";
这是一个完整的工作示例,您可以将其复制到控制台项目中并进行试用,以准确找出您需要的内容:
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; }
}
}
输出如下:
名称:比赛 1
地址:http://www.mywebsite.com/abc123.aspx
名称:比赛 2
地址:http://www.mywebsite.com/abc45.aspx
名称:比赛 3
地址:http://www.mywebsite.com/abc.5678.aspx
关于c# - 通过在字符串中搜索子字符串文本来获取字符串的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6132980/