当前位置: 首页>>代码示例>>C#>>正文


C# Regex.Split方法代码示例

本文整理汇总了C#中Regex.Split方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Split方法的具体用法?C# Regex.Split怎么用?C# Regex.Split使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Regex的用法示例。


在下文中一共展示了Regex.Split方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RegexSplit

    public static void RegexSplit()
    {
        string[] saExp = new string[] { "kkk", "lll", "mmm", "nnn", "ooo" };
        string[] saExp1 = new string[] { "kkk", "lll:mmm:nnn:ooo" };
        string[] saExp2 = new string[] { "kkk:lll", "mmm", "nnn:ooo" };
        string input = "kkk:lll:mmm:nnn:ooo";
        Regex regex = new Regex(":");

        // Split(string)
        string[] result = regex.Split(input);
        Assert.Equal(saExp, result);

        // A count of 0 means split all
        result = regex.Split(input, 0);
        Assert.Equal(saExp, result);

        // public static String[] Split(string input, Int32 count); ":"
        // "kkk:lll:mmm:nnn:ooo", 2
        result = regex.Split(input, 2);
        Assert.Equal(saExp1, result);

        // public static String[] Split(string input, Int32 count, Int32 startat); ":"
        // "kkk:lll:mmm:nnn:ooo", 3, 6
        result = regex.Split(input, 3, 6);
        Assert.Equal(saExp2, result);
    }
开发者ID:eerhardt,项目名称:corefx,代码行数:26,代码来源:RegexSplitTests.cs

示例2: Main

    static void Main()
    {
        // речник който да пази търсените думи като ключове, ако има съвпадение да инкрементира
        var words = new Dictionary<string, int>();

        string inputWords = Console.ReadLine().ToLower();
        while (inputWords != "end")
        {
            words.Add(inputWords, 0);
            inputWords = Console.ReadLine();
        }

        using (StreamReader reader = new StreamReader("../../../text.txt"))
        {
            Regex regex = new Regex(@"[^\w+]");

            //чете ред от файла и го слага в масив от думи (прави ги малки) за да обходим всяка
            string line = reader.ReadLine().ToLower();

            string[] wordsFromLine = regex.Split(line);        // ако файла е празен ще хвърли грешка

            while (line != null)
            {
                for (int i = 0; i < wordsFromLine.Length; i++)
                {
                    if (words.ContainsKey(wordsFromLine[i]))   //проверява за ключ
                    {
                        words[wordsFromLine[i]]++;
                    }
                    //Console.WriteLine(wordsFromLine[i]);
                }

                line = reader.ReadLine();
                if (line != null)                   //проверка за празен ред
                {
                    wordsFromLine = regex.Split(line.ToLower());
                }
            }
        }
        using (StreamWriter writer = new StreamWriter("../../results.txt"))
        {
            foreach (var item in words)
            {
                writer.WriteLine(item.Key + " - " + item.Value);
                //Console.WriteLine(item.Key + " - " + item.Value);
            }
        }
    }
开发者ID:teodory,项目名称:SoftUni-Homeworks,代码行数:48,代码来源:Problem3.cs

示例3: BitMaskUIScenesAttribute

	public BitMaskUIScenesAttribute()
	{
		Regex rootPath = new Regex(Regex.Escape("Assets/Scenes/")); /*+ Regex.Unescape(".+$")*/
		Regex ui = new Regex(".+(Panel)|(Popup)|(Screen)\\.unity");
		
		int size = 0;
		string[] allScenes = new string[UnityEditor.EditorBuildSettings.scenes.GetLength(0)];
		for(int i = 0 ; i < allScenes.Length ; i++)
		{
			allScenes[i] = UnityEditor.EditorBuildSettings.scenes[i].path;
			allScenes[i] = rootPath.Split(allScenes[i])[1];
			if(!ui.IsMatch(allScenes[i]) || !UnityEditor.EditorBuildSettings.scenes[i].enabled)
			{
				allScenes[i] = null;
			}
			else
				size++;
		}
		
		scenes = new string[size];
		int j = 0;
		for(int i = 0 ; i < allScenes.Length ; i++)
		{
			if(allScenes[i] != null)
			{
				scenes[j] = allScenes[i];
				j++;
			}
		}
	}
开发者ID:dannisliang,项目名称:FFEngine,代码行数:30,代码来源:BitMaskUIScenesAttribute.cs

示例4: Main

    static void Main()
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        Regex splitPattern = new Regex(@"\s*\|\s*");
        Dictionary<string, List<string>> winers = new Dictionary<string, List<string>>();
        string command = Console.ReadLine();
        while (command != "report")
        {
            string[] tokens = splitPattern.Split(command.Trim());
            string athlete = Regex.Replace(tokens[0].Trim(), @"\s+", " ");
            string country = Regex.Replace(tokens[1].Trim(), @"\s+", " ");

            if (!winers.ContainsKey(country))
            {
                winers.Add(country, new List<string>());
            }

            winers[country].Add(athlete);

            command = Console.ReadLine();
        }

        var orderedCountryData = winers
            .OrderByDescending(x => x.Value.Count);

        foreach (var country in orderedCountryData)
        {
            Console.WriteLine("{0} ({1} participants): {2} wins",
                country.Key,
                country.Value.Distinct().Count(),
                country.Value.Count);
        }
    }
开发者ID:Nitroto,项目名称:CSharp-Advanced-Exam-31.May.2015,代码行数:33,代码来源:04.+OlympicsAreComing.cs

示例5: DefaultWordBreaks

 public void DefaultWordBreaks()
 {
     Regex re = new Regex(@"\b");
     Assert.That(re.Split("The 'quick' (\"brown\") fox\r\ncan't ju\xFEFFmp 32.3 feet,\nright?"),
         Is.EqualTo(new string[] { "", "The", " ", "'", "quick", "'", " ", "(", "\"", "brown", "\"", ")", " ",
             "fox", "\r\n", "can't", " ", "ju\xFEFFmp", " ", "32.3", " ", "feet", ",", "\n", "right", "?", "" }));
 }
开发者ID:MichaelBrazier,项目名称:brasswork-regex,代码行数:7,代码来源:ModeTests.cs

示例6: createFromString

 public static RationalNumber createFromString(string initialString)
 {
     Regex slash = new Regex("/");
     string[] two_numbers = slash.Split(initialString);
     RationalNumber result = new RationalNumber(Convert.ToInt32(two_numbers[0]),
                                                Convert.ToUInt32(two_numbers[1]));
     return result;
 }
开发者ID:antonid08,项目名称:BSUIR_LABS,代码行数:8,代码来源:Program.cs

示例7: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        Label4.Text = (string)Session["sid"];
        Label5.Text = (string)Session["sname"];
        if (!IsPostBack)
        {
            //Panel1.Visible = false;
            //Panel2.Visible = false;
            Label1.Visible = false;
            //Label2.Visible = false;
            //TextBox1.Visible = false;
        }


        Session["data"] = TextBox1.Text;
        string text = TextBox1.Text;
        string splitby = " ";
        Regex rg = new Regex(splitby);
        string[] st = rg.Split(text);
        int m = st.Count();
        for (int k = 0; k < m; k++)
        {
            if (st[k].ToString() != "")
            {
                DataSet da = new DataSet();
                da = obj.filematching(st[k].ToString());

                if (da.Tables[0].Rows.Count > 0)
                {
                    for (int f = 0; f < da.Tables[0].Rows.Count; f++)
                    {
                      

                        // creation of linkbutton

                        LinkButton linkbutton = new LinkButton();
                        linkbutton.Text = da.Tables[0].Rows[f]["fname"].ToString() + "<br><br>";
                        linkbutton.Visible = true;
                        linkbutton.CommandName = da.Tables[0].Rows[f]["fname"].ToString();
                        linkbutton.Command += new CommandEventHandler(this.link_click);
                        linkbutton.ID = h.ToString();
                        this.downloadfiles.Controls.Add(linkbutton);
                        linkbutton.Visible = true;
                        Label3.Visible = true;
                        Panel4.Visible = true;
                        Panel6.Visible = true;
                        h++;

                    }
                }
                else
                {
                    MsgBox.Show("No files found");
                }
            }
        }
    }
开发者ID:gowrinath,项目名称:Public-Health-Care-System,代码行数:57,代码来源:searchafterlogin.aspx.cs

示例8: CurrencyConversion

 public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
 {
     WebClient web = new WebClient();
     string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
     string response = web.DownloadString(url);
     Regex regex = new Regex(@":(?<rhs>.+?),");
     string[] arrDigits = regex.Split(response);
     string rate = arrDigits[3];
     return rate;
 }
开发者ID:LuxF3rre,项目名称:Jquery-Files,代码行数:10,代码来源:WebService.cs

示例9: typeText

	public void typeText(string text,float delay)
		{
		if(label==null){
			sendFinishEvent();
			return;
		}
		label.text="";
		if(delay>0)
			defaultDelay=delay;
		
		string t=text;
//		t="asdb\\nasdg\\1.5hjkh\\nhjkhg";
		Regex reg=new Regex(@"\\n|\\\d{1,5}\.\d{0,2}|\\\d{1,5}");
		mc=reg.Matches(t);
		typingText=reg.Split(t);
		StopAllCoroutines();
		StartCoroutine(typing());
		}
开发者ID:SpacesAdventure,项目名称:Kio-2,代码行数:18,代码来源:TypeWriter.cs

示例10: FindOccurrences

 static List<int> FindOccurrences(string fileName, List<string> words)
 {
     List<int> occurences = new List<int>();
         StreamReader streamReader = null;
         try
         {
             streamReader = new StreamReader(fileName);
             string text = streamReader.ReadToEnd();
             foreach (var item in words)
             {
                 string pattern = string.Format(@"\b{0}\b", item);
                 Regex regex = new Regex(pattern);
                 occurences.Add(regex.Split(text).Length - 1);
             }
         }
         catch (FileNotFoundException)
         {
             Console.WriteLine("The file {0} cannot be found", fileName);
         }
         catch (DirectoryNotFoundException)
         {
             Console.WriteLine("The file {0} is not in this directory", fileName);
         }
         catch (PathTooLongException)
         {
             Console.WriteLine("You gave too long path");
         }
         catch (ArgumentNullException)
         {
             Console.WriteLine("Cannot use null arguments");
         }
         catch (ArgumentException)
         {
             Console.WriteLine("You cannot use blank path or special characters for a path");
         }
         finally
         {
             if (streamReader != null)
             {
                 streamReader.Dispose();
             }
         }
         return occurences;
 }
开发者ID:kalinnikol,项目名称:TelerikAcademy-1,代码行数:44,代码来源:NumberOfOccurrencesOfAWordInFile.cs

示例11: FixContentHistory

 public string FixContentHistory(ContentData myContentData, string curSnippet)
 {
     Regex regExp;
         regExp = new Regex(" ");
         foreach (string strLineVal in regExp.Split(curSnippet))
         {
             regExp = new Regex("=");
             string[] strKeyValues;
             strKeyValues = regExp.Split(strLineVal);
             if ((string) (strKeyValues[0].Trim()) == "src")
             {
                 string curStringVal = strKeyValues[1];
                 if (curStringVal.ToLower().IndexOf("/assets") >= 0)
                 {
                     curStringVal = (string) (curStringVal.ToLower().Replace("/assets/" + myContentData.AssetData.Id.ToLower() + myContentData.AssetData.Version.Substring(myContentData.AssetData.Version.IndexOf(".")).ToLower(), "/assetmanagement/DownloadAsset.aspx?history=true&ID=" + myContentData.AssetData.Id + "&version=" + myContentData.AssetData.Version));
                     curSnippet = Regex.Replace(curSnippet, strKeyValues[1], curStringVal);
                 }
             }
         }
         return curSnippet;
 }
开发者ID:jaytem,项目名称:minGit,代码行数:21,代码来源:ViewHistory.ascx.cs

示例12: DoSomething

  static void DoSomething ()
  {
    Trace curTrace = (Trace)FindObjectOfType( typeof(Trace) );

    var list = new List<WayPoint>();
    var rgx = new Regex(@"\d+$");

    //Selection.gameObjects doesn't hold selection order
    foreach( var obj in FindObjectsOfType(typeof(WayPoint)) )
    {
      var wp = (WayPoint)obj;

      list.Add(wp);
      wp.name = rgx.Split(obj.name)[0] + wp.editorPriority.ToString("D2");
      wp.trace = curTrace;
    }

    list.Sort( (t1, t2) => t1.editorPriority - t2.editorPriority );
    //ths.wayPoints = list.Select( (v) => v.gameObject ).ToArray();
    curTrace.wayPoints = list.ToArray();
  }
开发者ID:Auguraculums,项目名称:BirdFlock,代码行数:21,代码来源:Trace.cs

示例13: DataBtn_Click

    protected void DataBtn_Click(object sender, EventArgs e)
    {
        //the database data we wish to enter
        //StreamReader langfile = new StreamReader("C:\\Users\\Zimmy\\Documents\\Snippit\\Languages\\" + TextBox1.Text);
        StreamReader langfile = new StreamReader(Directory.GetCurrentDirectory() + @"\Languages\" + TextBox1.Text);

        //Establish an SQL connection
        string connectString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Zimmy\Documents\Snippit\App_Data\Database.mdf;Integrated Security=True;User Instance=True;Asynchronous Processing=true";
        SqlConnection conn = new SqlConnection(connectString);
        conn.Open();

        string command;                 //the string contating the SQL command we wish to execute
        SqlCommand insert;              //the SQL command that will be executed

        string[] cols = new string[4];  //holds each column value for each row of data

        Regex splitter = new Regex(@"(\t)");    //each column of data is separated by a tab
        string line;                            //a line of text that is read in

        while((line = langfile.ReadLine()) != null)
        {
            cols = splitter.Split(line);    //split line up by tabs (NOTE: This makes each tab into a token as well.
                                            //                              Must figure out a way around this.

            //Insert the row of data into the database
            command = "INSERT INTO " + DropDownList2.SelectedValue + " VALUES ('" + cols[0] + "', '" + cols[2] + "', '" + cols[4] + "','" + cols[6] + "')";
            insert = new SqlCommand(command, conn);
            insert.ExecuteNonQuery();

        }

        //close the SQL connection
        conn.Close();

        //close the StreamReader
        langfile.Close();
    }
开发者ID:chriszimmerman,项目名称:snippit,代码行数:37,代码来源:AddToDB.aspx.cs

示例14: Main

    static void Main()
    {
        const string SplitPattern = @"\s*\|\s*";
        var regex = new Regex(SplitPattern);

        var report = new Dictionary<string, List<string>>();

        string input = Console.ReadLine();

        while (input != "report")
        {
            string[] info = regex.Split(input.Trim());

            string participant = Regex.Replace(info[0].Trim(),@"\s+", " " );
            string country = Regex.Replace(info[1].Trim(), @"\s+", " ");

            if (!report.ContainsKey(country))
            {
                report[country] = new List<string>();
            }
            report[country].Add(participant);

            input = Console.ReadLine();
        }

        var output = report.OrderByDescending(r => r.Value.Count);

        foreach (var data in output)
        {
            Console.WriteLine("{0} ({1} participants): {2} wins",
                data.Key,
                data.Value.Distinct().Count(),
                data.Value.Count
                );
        }
    }
开发者ID:alvelchev,项目名称:SoftUni,代码行数:36,代码来源:Olympics.cs

示例15: BitMaskToUiScenes

	public static string[] BitMaskToUiScenes(int a_bitMask)
	{
		Regex rootPath = new Regex(Regex.Escape("Assets/Scenes/")); /*+ Regex.Unescape(".+$")*/
		Regex ui = new Regex(".+(Panel)|(Popup)|(Screen)\\.unity");
		
		int size = 0;
		string[] allScenes = new string[UnityEditor.EditorBuildSettings.scenes.GetLength(0)];
		for(int i = 0 ; i < allScenes.Length ; i++)
		{
			allScenes[i] = UnityEditor.EditorBuildSettings.scenes[i].path;
			allScenes[i] = rootPath.Split(allScenes[i])[1];
			if(!ui.IsMatch(allScenes[i]) || !UnityEditor.EditorBuildSettings.scenes[i].enabled || ((1 << size) & a_bitMask) != (1 << size))
			{
				allScenes[i] = null;
			}
			else
				size++;
		}
		
		string[] scenes = new string[size];
		int j = 0;
		for(int i = 0 ; i < allScenes.Length ; i++)
		{
			if(allScenes[i] != null)
			{
				string[] split = allScenes[i].Split('/');
				string scene = split[split.Length-1];
				string[] test = {"."};
				scene = scene.Split(test, System.StringSplitOptions.RemoveEmptyEntries)[0];
				scenes[j] = scene;
				j++;
			}
		}
		
		return scenes;
	}
开发者ID:dannisliang,项目名称:FFEngine,代码行数:36,代码来源:FFUtils.cs


注:本文中的Regex.Split方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。