如何获得特定单词之后和字符串中另一个单词上的子字符串

说我有字符串“ Old Macdonald拥有一个农场等等”。我想获取子字符串“有一个农场”。在工作“麦克唐纳”之后,直到“农场”一词,我想得到任何东西

因此,字符串中的常量为:

“麦克唐纳德”-我不想包含在子字符串中

“农场”-我想在子字符串中包含该词和结尾词

我一直在尝试合并indexof等函数,但似乎无法使其正常工作


犯罪嫌疑人X
浏览 176回答 3
3回答

炎炎设计

你可以使用RegEx与(?<=Macdonald\s).*(?=\sand)解释正向后看&nbsp;(?<=Macdonald\s)MacdonaldMacdonald从字面上匹配字符\s&nbsp;匹配任何空格字符.*&nbsp;匹配任何字符(行终止符除外)*&nbsp;量词-在零次和无限制次数之间进行匹配,并尽可能多地匹配,并根据需要返回(贪婪)积极向前&nbsp;(?=\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){&nbsp; &nbsp; Console.WriteLine(match.Value);}else{&nbsp; &nbsp; Console.WriteLine("No farms for you");}输出had a farm

一只萌萌小番薯

正如我在评论中提到的那样,我建议使用Regex(TheGeneral建议的方式)。但是还有另一种方法可以做到这一点。将其添加为解决方法&nbsp; &nbsp; &nbsp; &nbsp; string input = "Old Macdonald had a farm and on";&nbsp; &nbsp; &nbsp; &nbsp; List<string> words = input.Split(" ".ToCharArray()).ToList();&nbsp; &nbsp; &nbsp; &nbsp; string finalString = "";&nbsp; &nbsp; &nbsp; &nbsp; int indexOfMac = words.IndexOf("Macdonald");&nbsp; &nbsp; &nbsp; &nbsp; int indexOfFarm = words.IndexOf("farm");&nbsp; &nbsp; &nbsp; &nbsp; if (indexOfFarm != -1 && indexOfMac != -1 &&&nbsp; //if word is not there in string, index will be '-1'&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; indexOfMac < indexOfFarm)&nbsp; //checking if 'macdonald' comes before 'farm' or not&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //looping from Macdonald + 1 to farm, and make final string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i = indexOfMac + 1; i <= indexOfFarm; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; finalString += words[i] + " ";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; finalString = "No farms for you";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(finalString);
打开App,查看更多内容
随时随地看视频慕课网APP