C#:字符串分割返回一个字符串列表和分隔符的列表? [英] C#: String split returning list of strings AND list of delimiters?
本文介绍了C#:字符串分割返回一个字符串列表和分隔符的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有在C#中的任何内置的方式来分割文本文字和分隔符的数组?
我想要的是:
Is there any inbuilt way in C# to split a text into an array of words and delimiters? What I want is:
text = "word1 + word2 - word3";
string[] words = text.Split(new char[] { '+', '-'});
//Need list '+', '-' here?
任何想法?很显然,我可以只处理由手工文字...:)
Any ideas? Obviously I can just process the text by hand... :)
推荐答案
使用Regex.split()与捕获括号<一个HREF =http://msdn.microsoft.com/en-us/library/byy2946e.aspx相对=nofollow> http://msdn.microsoft.com/en-us/library/byy2946e.aspx 一>
Use Regex.split() with capturing parentheses http://msdn.microsoft.com/en-us/library/byy2946e.aspx
string input = @"07/14/2007";
string pattern = @"(-)|(/)";
foreach (string result in Regex.Split(input, pattern))
{
Console.WriteLine("'{0}'", result);
}
// In .NET 1.0 and 1.1, the method returns an array of
// 3 elements, as follows:
// '07'
// '14'
// '2007'
//
// In .NET 2.0, the method returns an array of
// 5 elements, as follows:
// '07'
// '/'
// '14'
// '/'
// '2007'
这篇关于C#:字符串分割返回一个字符串列表和分隔符的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文