Regular Expression 正則表達式-1 (C#)
2024-07-21 02:18:54
供稿:網友
起因是因為一片帖子,問到了一個問題,帖子是這樣的:
originally posted by 人就是這樣
我想編一個程序,但學compsci是很久以前的事情了。想請教請教大家。
有兩個txt文件,一個叫source.txt(有很多數據), 一個叫target.txt(空白的)
我想把source.txt里的一些數據提取出來(稍微修改一下),然后寫到target.txt里面。
舉個例子:
sourse.txt里的數據:
2oi)[email protected]##( "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(正則表達式),只不過自己總因為正則表達式晦澀難懂,因此沒有好好的琢磨過。
于是我就打算借這個機會把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給與指正。