发布于 4年前

C# 如何获取字符串中某段字符

问题描述

C# 获取字符串中某段字符,写一个方法

(参数1 字符串内容,参数2,参数1中的起始字符,参数3 参数1中的结束字符)

举例:

string str = "爸爸给我买了一盆仙人掌,它的刺可扎手了!但是它圆的像太阳。我每天给它浇水,我可喜欢它了!我还用一个漂亮的盆子来养它。我妈妈还特地为它买一些营养土。我真喜欢仙人掌。";
方法:(str,"爸爸",“仙人掌”);
输出:给我买了一盆

解决方案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace HelloWorldApplication
{
   class HelloWorld
   {
        static string 方法(string str, string s1, string s2)
        {
            string esc = "\\()[]-=+*,.\"'!^$?<>{}";
            foreach (var item in esc)
            {
                s1 = s1.Replace(item.ToString(), "\\" + item.ToString());
                s2 = s2.Replace(item.ToString(), "\\" + item.ToString());
            }
            string pattern = string.Format("(?<={0}).*?(?={1})", s1, s2);
            return Regex.Match(str, pattern, RegexOptions.Multiline).Value;
        }

        static void Main(string[] args)
        {
            string str = "爸爸给我买了一盆仙人掌,它的刺可扎手了!但是它圆的像太阳。我每天给它浇水,我可喜欢它了!我还用一个漂亮的盆子来养它。我妈妈还特地为它买一些营养土。我真喜欢仙人掌。";
            string result = 方法(str,"爸爸", "仙人掌");
            Console.WriteLine(result);
        }
   }
}
©2020 edoou.com   京ICP备16001874号-3