C# 從字符串中提取指定字符類型的內容

從一段字符串中,提取中文、英文、數字正則表達式

中文字符30Margin中文字符40HorizontalAlignmentspa

正則表達式:code

 1     /// <summary>
 2     /// 英文字母與數字
 3     /// </summary>
 4     public const string LettersAndNumbers = "[a-zA-Z0-9]+";
 5 
 6     /// <summary>
 7     /// 中文字符
 8     /// </summary>
 9     public const string ChineseChars = "[\u4E00-\u9FA5]+";
10 
11     /// <summary>
12     /// 英文字符
13     /// </summary>
14     public const string EnglishChars = "[a-zA-Z]+";

 PS:使用正則匹配字符內容,不能使用開始、結束字符( ^文本開始; $文本結束)。blog

Regex使用:字符串

1 string ChineseChars = "[\u4E00-\u9FA5]+";
2 var match = Regex.Match("中文字符30Margin中文字符40HorizontalAlignment", ChineseChars, RegexOptions.IgnoreCase);
3 var result = $"Index:{match.Index},Length:{match.Length}\r\nResult:{match.Value}";

注:string

Regex.Match只會返回第一個匹配項io

若是須要獲取正則對應的全部匹配項,可使用 Regex.Matchesclass

相關文章
相關標籤/搜索