asp.net一些常用字串操作Regex

來源:互聯網
上載者:User

1.拆分字串
1.1 以下例舉一個拆分句子的demo:

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("請輸入要分拆的字串,並按Enter鍵確認。");
string input=Console.ReadLine();
string pattern=@".|,|:|;|。|,|:|;";
string[] rs=Regex.Split(input,pattern);
Console.WriteLine("拆分後的所包含的分句為:");
foreach (string s in rs)
{
Console.WriteLine(s);
}
Console.ReadKey(true);
}
}
}

1.2 拆分HTML標籤

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Program
{
public static void Main(string[] args)
{
string input="<b>這是</b><b>一個</b><b>寂寞的天。</b><b>下著</b><b>有點</b><b>傷心地</b><b>雨。</b>";
string pattern="<[^>]*>";
Regex r=new Regex(pattern);
string[] rs=r.Split(input);
Console.WriteLine("拆分後的所包含的分句為:");
foreach (string s in rs)
{
Console.WriteLine(s);
}
Console.ReadKey(true);
}
}
}

--------------------------------------------------------------------------------
2.查詢字串
Regex類提供了三個方法來實現字串的查詢和匹配,Match,Matchs和IsMatch.
2.1 Match在指定的輸入字串中搜尋Regex建構函式中指定的Regex,返回一個Match類對象,如果Match類對象的Success屬性為true,則存在匹配的字串,這個在前面的博文裡已經說明了,可以使用NextMatch進行下一次匹配。
下面的例子尋找HTML片段中所有帶引號的URL

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Test
{
static void PrintURL(string s)
{
string pattern="href\s*=\s*"[^"]*"";
Match m=Regex.Match(s,pattern);
while(m.Success)
{
Console.WriteLine(m.Value);
m=m.NextMatch();
}
}
public static void Main()
{
PrintURL("href="http:\\www.baidu.com" href="http:\\www.soso.com"");
Console.ReadKey();
}
}
}

--------------------------------------------------------------------------------
2.2 上面的例子也可以簡化的返回一個MatchCollection集合,利用foreach遍曆:

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Test
{
static void PrintURL(string s)
{
string pattern="href\s*=\s*"[^"]*"";
MatchCollection m=Regex.Matches(s,pattern);
foreach(Match str in m)
{
Console.WriteLine(str);
}
}
public static void Main()
{
PrintURL("href="http:\\www.baidu.com" href="http:\\www.soso.com"");
Console.ReadKey();
}
}

 
假如我們僅僅想知道引用的地址可以使用擷取的群組及Match類的Groups屬性。例如:
 

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Test
{
static void PrintURL(string s)
{
string pattern="href\s*=\s*"([^"]*)"";
MatchCollection m=Regex.Matches(s,pattern);
foreach(Match str in m)
{
Console.WriteLine(str.Groups[0] );
}
}
public static void Main()
{
PrintURL("href="http:\\www.111cn.net" href="http:\\www.soso.com"");
Console.ReadKey();
}
}
}

--------------------------------------------------------------------------------


2.3.1 IsMatch指示Regex再輸入字串中是否找到匹配項。
尋找是否在字元創中包含<a>

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Program
{
public static void Main(string[] args)
{
Regex r=new Regex ("<a[^>]*>",RegexOptions.IgnoreCase);
if(r.IsMatch("<a href="http://www.baidu.com/">連結</a>"))
Console.WriteLine("包含<a>標籤");
else
Console.WriteLine("不包含<a>標籤");
Console.ReadKey(true);
}
}
}

2.3.2用來驗證輸入16個數字

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Program
{
public static void Main(string[] args)
{
Regex r=new Regex (@"^d{4}-d{4}-d{4}-d{4}$");
if(r.IsMatch("1216-2593-3395-2612"))
Console.WriteLine("通過");
else
Console.WriteLine("不通過");
Console.ReadKey(true);
}
}
}

--------------------------------------------------------------------------------

3.替換字串
Regex類的Replace方法用來替換字串。下面的代碼將輸入字串中的"China"都替換為“中國”。

 代碼如下 複製代碼
using System;
using System.Text.RegularExpressions;
namespace RegexSplit
{
class Test
{
static void EtoC(string s)
{
Console.WriteLine("源字串:n{0}",s);
Console.WriteLine("替換後為:");
Console.WriteLine(Regex.Replace(s,"China","中國"));
}
public static void Main()
{
EtoC("China啊我的祖國,China啊China!");
Console.ReadKey();
}
}
}

例如,下面的函數示範了如何使用Regex驗證郵遞區號:

 代碼如下 複製代碼
private void ValidateZipButton_Click(object sender, System.EventArgs e)
{
   String ZipRegex = @"^d{5}$";
   if(Regex.IsMatch(ZipTextBox.Text, ZipRegex))
   {
      ResultLabel.Text = "ZIP is valid!";
   }
   else
   {
      ResultLabel.Text = "ZIP is invalid!";
   }
}

類似的,可以使用靜態 Replace() 方法將匹配替換為特定字串,如下所示:

String newText = Regex.Replace(inputString, pattern, replacementText);
最後,可以使用如下代碼遍曆輸入字串的匹配集合:

 代碼如下 複製代碼
private void MatchButton_Click(object sender, System.EventArgs e)
{
   MatchCollection matches = Regex.Matches(SearchStringTextBox.Text,
MatchExpressionTextBox.Text);
   MatchCountLabel.Text = matches.Count.ToString();
   MatchesLabel.Text = "";
   foreach(Match match in matches)
   {
      MatchesLabel.Text += "Found" + match.ToString() + " at
position " + match.Index + ".<br>";
   }
}

通常,在您需要指定預設以外的方式時,需要執行個體化 Regex 類的執行個體。特別是在設定選項時。例如,要建立忽略大小寫和模式空白地區的 Regex 執行個體,然後檢索與該運算式匹配的集合,則應使用如下代碼:

 代碼如下 複製代碼

Regex re = new Regex(pattern,
   RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
MatchCollection mc = re.Matches(inputString);

http url驗證

 代碼如下 複製代碼

Public Function IsValidUrl(ByVal Url As String) As Boolean
       Dim strRegex As String = "^(https?://)" _
                                 & "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" _
                                 & "(([0-9]{1,3}.){3}[0-9]{1,3}" _
                                 & "|" _
                                 & "([0-9a-z_!~*'()-]+.)*" _
                                 & "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]." _
                                 & "[a-z]{2,6})" _
                                 & "(:[0-9]{1,4})?" _
                                 & "((/?)|" _
                                 & "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"

        Dim re As RegularExpressions.Regex = New RegularExpressions.Regex(strRegex)
        MessageBox.Show("IP: " & Net.IPAddress.TryParse(Url, Nothing))
        If re.IsMatch(Url) Then
            Return True
        Else
            Return False
        End If
End Function

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.