为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
犯罪嫌疑人X 2021-04-08 18:15:14
说我有字符串“ Old Macdonald拥有一个农场等等”。我想获取子字符串“有一个农场”。在工作“麦克唐纳”之后,直到“农场”一词,我想得到任何东西因此,字符串中的常量为:“麦克唐纳德”-我不想包含在子字符串中“农场”-我想在子字符串中包含该词和结尾词我一直在尝试合并indexof等函数,但似乎无法使其正常工作
查看完整描述

3 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

你可以使用RegEx(?<=Macdonald\s).*(?=\sand)

解释

  • 正向后看 (?<=Macdonald\s)

    • MacdonaldMacdonald从字面上匹配字符

    • \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


查看完整回答
反对 回复 2021-04-24
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

正如我在评论中提到的那样,我建议使用Regex(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);


查看完整回答
反对 回复 2021-04-24
  • 3 回答
  • 0 关注
  • 170 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信