[英]Regular Expression to Split String
我正在嘗試編寫正則表達式來拆分以下字符串
"17. Entertainment costs,16. Employee morale, health, and welfare costs,3. Test"
成
17. Entertainment costs
16. Employee morale, health, and welfare costs
3. Test
請注意第二個字符串中的逗號。
我正在努力
static void Main(string[] args) {
Regex regex = new Regex( ",[1-9]" );
string strSplit = "1.One,2.Test,one,two,three,3.Did it work?";
string[] aCategories = regex.Split( strSplit );
foreach (string strCat in aCategories) {
System.Console.WriteLine( strCat );
}
}
但#不會通過
1.One
.Test,one,two,three
.Did it work?
那是因為你正在分裂(例如) ,2
- 2
被認為是分隔符的一部分,就像逗號一樣。 要解決此問題,您可以使用前瞻斷言 :
Regex regex = new Regex( ",(?=[1-9])" );
意思是“逗號,只要逗號后跟一個非零數字”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.