对于您的要求,我看到两种选择:
(1) 删除初始前缀字符(如果存在)。
(2) 使用完整的正则表达式来分隔字符串。
这段代码说明了两者:
using System;
using System.Linq;
using System.Text.RegularExpressions;
class APP { static void Main() {
string s = "~Peter~Lois~Chris~Meg~Stewie";
// #1 - Trim+Split
Console.WriteLine ("[#1 - Trim+Split]");
string[] result = s.TrimStart('~').Split('~');
foreach (string t in result) { Console.WriteLine("'"+t+"'"); }
// #2 - Regex
Console.WriteLine ("[#2 - Regex]");
Regex RE = new Regex("~([^~]*)");
MatchCollection theMatches = RE.Matches(s);
foreach (Match match in theMatches) { Console.WriteLine("'"+match.Groups[1].Value+"'"); }
// #3 - Regex with LINQ [ modified from @ccook's code ]
Console.WriteLine ("[#3 - Regex with LINQ]");
Regex.Matches(s, "~([^~]*)")
.OfType<Match>()
.ToList()
.ForEach(m => Console.WriteLine("'"+m.Groups[1].Value+"'"))
;
}}
Run Code Online (Sandbox Code Playgroud)
#2 中的正则表达式匹配分隔符,后跟包含零个或多个非分隔符的匹配组。结果匹配是分隔字符串(包括任何空字符串)。对于每个匹配,“match.Value”是包括前导分隔符的整个字符串,“match.Groups 1 .Value”是包含无分隔符字符串的第一个匹配组。
为了完整起见,包含第三种编码 (#3),显示与 #2 中相同的正则表达式方法,但采用 LINQ 编码风格。
如果您在正则表达式方面遇到困难,我强烈推荐Jeffrey EF Friedl 的《掌握正则表达式,第三版》。到目前为止,它是理解正则表达式的最佳帮助,并且可以根据需要在以后作为极好的参考或复习。
归档时间: |
|
查看次数: |
10066 次 |
最近记录: |