正则表达式匹配分析工具 C#编写
引言
嵌入式協同開發時經常會用到靜態鏈接庫文件(拓展名為.a),即.c文件編譯的庫。有時我們需要知道某個庫打包了哪些c文件,通常可以用文本編輯器打開并查找,但是對于較復雜的庫這樣查找會非常麻煩,利用正則表達式則可以輕松解決。本文正是介紹一個使用C#開發的正則表達式匹配工具,該工具可從文本文件中一鍵提取出所有匹配項。
使用介紹
使用本工具需要熟悉正則表達式,可參考正則表達式教程?https://www.runoob.com/regexp/regexp-tutorial.html?。
本工具界面如下:
首先點擊“打開”按鈕,打開需要分析的文本文件。測試用“.a” 文本內容局部如下圖,我們需要在其中找出需要的信息。
輸入正則表達式
[a-zA-Z][a-zA-Z0-9_]*[\.][o]以查找類似“xx.o”的字符串,點擊“分析”按鈕,即可查找并列出所有匹配項。
?
源碼解析
1.正則表達式分析類
新建一個類用于正則表達式分析及存儲結果。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks;namespace RegExpAnalyst {class RegExpAnalysis{public List<string> matches = new List<string>();public string errorCode;/// <summary>/// 正則表達式分析/// </summary>/// <param name="input">要分析的字符串內容</param>/// <param name="pattern">正則表達式</param>/// <returns></returns>public bool Analysis(string input, string pattern){try{foreach (Match item in Regex.Matches(input, pattern)){matches.Add(item.Value);}}catch (Exception e){errorCode = e.Message;return false;}return true;}} }2.打開文件操作
這里僅記錄文件路徑。
private void Button_Open_Click(object sender, RoutedEventArgs e) {OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();ofd.Filter = "全部文件|*";if (ofd.ShowDialog() == true){//此處做你想做的事 ...=ofd.FileName; textBox_file.Text = ofd.FileName;filePath = ofd.FileName;TextBox_Msg.Text = "";} }3.分析按鈕操作
這里首先打開文件并讀取到文件內容存入content,然后實例化一個RegExpAnalysis對象,并調用分析函數。分析函數會查找匹配項并存入matches,最后我們將matches內容輸出到TextBox即可,如果分析出錯則顯示錯誤信息。
private void Button_Show_Click(object sender, RoutedEventArgs e) {String content;FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);StreamReader sr = new StreamReader(fs);content = sr.ReadToEnd();fs.Close();sr.Close();//分析RegExpAnalysis regExp = new RegExpAnalysis();if (regExp.Analysis(content, textBox_Regexp.Text)){TextBox_Msg.Text = String.Format("匹配數量:{0}\n", regExp.matches.Count);foreach (var item in regExp.matches){TextBox_Msg.Text += (item + "\n");}}else{TextBox_Msg.Text = regExp.errorCode + "\n";} }?
資源下載
工具下載:https://download.csdn.net/download/xiaoqvae/14021550
源碼下載:https://download.csdn.net/download/xiaoqvae/14021585
?
?
總結
以上是生活随笔為你收集整理的正则表达式匹配分析工具 C#编写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有一根27厘米的细木杆java_百度笔试
- 下一篇: HBM显存