技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運(yùn)營

贊助商

分類目錄

贊助商

最新文章

搜索

[4示例]C#使用正則表達(dá)式Regex.split分割字符串

作者:admin    時(shí)間:2023-5-4 15:36:41    瀏覽:

分割字符串在程序編寫中常常要用到,不管哪種語言。本文要介紹的是,在C#中如何使用正則表達(dá)式Regex.split分割字符串,文中用了4個(gè)示例來演示。

為了便于使用,Regex 添加了以下用于拆分字符串的名稱空間。

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

示例 1

使用正則表達(dá)式從字符串中拆分?jǐn)?shù)字。

string Text = "1 One, 2 Two, 3 Three is good.";  
  
string[] digits = Regex.Split(Text, @"\D+");  
  
foreach (string value in digits)  
{  
    int number;  
    if (int.TryParse(value, out number))  
    {  
        Console.WriteLine(value);  
    }  

上面的代碼使用 \D+ 拆分字符串并循環(huán)檢查編號(hào)并打印。

輸出

1
2
3

示例 2

使用正則表達(dá)式從字符串中拆分操作。

string operation = "315 / 1555 = 0";  
  
string[] operands = Regex.Split(operation, @"\s+");  
  
foreach (string operand in operands)  
{  
    Console.WriteLine(operand);  
}

上面的代碼使用 \s+ 拆分字符串并循環(huán)打印。

輸出

315
/
1555
=
0

示例 3

使用 /char 從字符串中拆分 URL 或路徑。

string URL = "C:/TestApplication/1";  
  
string[] splitString = Regex.Split(URL, @"/");  
  
foreach (var item in splitString)  
{  
    Console.WriteLine(item);  

輸出

C:
TestApplication
1

示例4

使用正則表達(dá)式從字符串中有大寫單詞的位置拆分字符串。

string sentence = "Hello This Is testing application for Split STring";  
  
string[] uppercaseWords = Regex.Split(sentence, @"\W");  
  
//var list = new List();  這樣寫不對(duì)?
List<String> list = new List<String>();

foreach (string value in uppercaseWords)  
{  
    if (!string.IsNullOrEmpty(value) &&  
        char.IsUpper(value[0]))  
    {  
        list.Add(value);  
    }  
}  
  
foreach (var value in list)  
{  
    Console.WriteLine(value);  

上面的代碼使用 \W 拆分字符串,將語句中包含大寫字母的字符串拆分并存入列表。完成第一個(gè)循環(huán)后,第二個(gè)循環(huán)顯示單詞中包含大寫字母的所有單詞。

輸出

Hello
This
Is
Split
STring

總結(jié)

本文通過4個(gè)示例介紹了C#使用正則表達(dá)式Regex.split分割字符串的方法。

x
  • 站長推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */