Regular Expression Regex-1 (C#)

來源:互聯網
上載者:User

起因是因為一片文章,問到了一個問題,文章是這樣的:

Originally Posted by 人就是這樣
我想編一個程式,但學CompSci是很久以前的事情了。想請教請教大家。

有兩個txt檔案,一個叫source.txt(有很多資料), 一個叫target.txt(空白的)

我想把source.txt裡的一些資料提取出來(稍微修改一下),然後寫到target.txt裡面。

舉個例子:
sourse.txt裡的資料:
2oi)4@##( "data:001%abc">dsi-23)(*32##("data:dce%xy3"#(*EOIj2308Eld

想提取的資料就是橘黃色的。
data:001%abc

全部提取出來以後,我還想把%換成*, 然後每條資料後面加個逗號","

最後target.txt就應該這樣:

data:001*abc,
data:dce*xyz

請問應該怎麼做啊?實在JAVA忘光了。求教~~

如果幫我做的話付點酬勞也可以。

以前我也面臨過類似的問題,總是通過程式描述的辦法解決,現在問題又提起來了,於是靜下心來想一想。有了上學期330編譯原理的基礎,並且做過有限狀態自動機以後,已經非常明確這種文文書處理的事情應該交給Regular Expression(Regex),只不過自己總因為Regex晦澀難懂,因此沒有好好的琢磨過。於是我就打算借這個機會把Regular Expression好好的熟悉一下。結果發現程式原來如此好寫:using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace RegExpression
{
    /// <summary>
    ///
    /// </summary>
    public class DataFilter
    {
        public static void Main(string[] args)
        {
            if( args.Length < 2 )
            {
                Console.Error.WriteLine("Please enter 2 filenames(e.g. In.txt Out.txt)");
                return;
            }
            string Result;
            using( StreamReader sr = new StreamReader(args[0]) )
            {
                Result = Filter( sr.ReadToEnd() );
            }
            using( StreamWriter wr = new StreamWriter(args[1]) )
            {
                wr.Write(Result);
            }
        }
        private static string Filter(string input)
        {
            StringBuilder result = new StringBuilder();
            Regex r = new Regex("/"(?<data>//w+):(?<key>//w+)%(?<value>//w+)/"", RegexOptions.Compiled);
            for( Match m = r.Match(input); m.Success; m = m.NextMatch() )
            {
                result.Append( m.Result("${data}:${key}*${value},"+Environment.NewLine) );
            }
            return result.ToString();
        }
    }
}
實現這個功能的關鍵代碼也就不超過10行就夠了,一個字,爽。略加修正:·using statement·end of line (Environment.NewLine)·use StringBuilder to improve performence這些要感謝cumcum給與指正。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.