簡體   English   中英

正則表達式到Split String

[英]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?

您可以使用前瞻 (?=...) ,就像在此表達式中一樣:

@",(?=\s*\d+\.)"

刪除\\s*如果你不想讓之間的空間,在和N.

那是因為你正在分裂(例如) ,2 - 2被認為是分隔符的一部分,就像逗號一樣。 要解決此問題,您可以使用前瞻斷言

        Regex regex = new Regex( ",(?=[1-9])" );

意思是“逗號,只要逗號后跟一個非零數字”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM