说我有字符串“老麦克唐纳有一个农场和”。 我想让子串“有一个农场”。 我希望在工作“麦克唐纳”之后得到任何东西,直到“农场”这个词
所以字符串中的常量是:
“Macdonald” - 我不希望将其包含在子字符串
中“farm” - 我想要包含的内容和子字符串中的结束字
我一直在尝试合并indexof等功能,但似乎无法让它工作
答案 0 :(得分:5)
您可以将RegEx
与(?<=Macdonald\s).*(?=\sand)
解释
(?<=Macdonald\s)
Macdonald
字面匹配字符Macdonald
\s
匹配任何空格字符 .*
匹配任何字符(行终止符除外)
*
量词 - 在零和无限次之间匹配,尽可能多次,根据需要回馈(贪婪) 积极前瞻 (?=\sand)
\s
匹配任何空白字符,并按字面匹配字符and
示例强>
var input = "Old Macdonald had a farm and on";
var regex = new Regex(@"(?<=Macdonald\s).*(?=\sand)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var match = regex.Match(input);
if (match.Success)
{
Console.WriteLine(match.Value);
}
else
{
Console.WriteLine("No farms for you");
}
输出
had a farm
答案 1 :(得分:0)
正如我在评论中提到的,我建议使用正则表达式(TheGeneral建议的方式)。但还有另一种方法可以做到。
将其添加为变通方法
string input = "Old Macdonald had a farm and on";
List<string> words = input.Split(" ".ToCharArray()).ToList();
string finalString = "";
int indexOfMac = words.IndexOf("Macdonald");
int indexOfFarm = words.IndexOf("farm");
if (indexOfFarm != -1 && indexOfMac != -1 && //if word is not there in string, index will be '-1'
indexOfMac < indexOfFarm) //checking if 'macdonald' comes before 'farm' or not
{
//looping from Macdonald + 1 to farm, and make final string
for(int i = indexOfMac + 1; i <= indexOfFarm; i++)
{
finalString += words[i] + " ";
}
}
else
{
finalString = "No farms for you";
}
Console.WriteLine(finalString);
答案 2 :(得分:0)
您可以使用IndexOf()和Substring()作为
string input = "Old Macdonald had a farm and on";
int pos=input.IndexOf("Macdonald");
if(pos > -1){
string s2=input.Substring(pos);
string second="farm";
int secLen=second.Length;
int pos2=s2.IndexOf(second);
if(pos2 > -1){
Console.WriteLine("Substring: {0}", s2.Substring(0,pos2+secLen));
}
}
答案 3 :(得分:0)
当然,Linq不能被排除在解决方案列表之外:
string SearchString = "Old Macdonald had a farm and on";
string fromPattern = "Macdonald";
string toPattern = "farm";
string result = string.Join(" ", SearchString
.Split((char)32)
.SkipWhile(s => s != fromPattern)
.Skip(1)
.TakeWhile(s => s != toPattern)
.Append(toPattern));