Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9374

C#(csc.exe)だけで導入できる正規表現で検索置換する簡易ツールつくった【自分用】

$
0
0

色々とインストールができないお堅い環境にいて、正規表現検索すらままならないので、つくってみた。
Windowsでcsc.exeさえあれば導入可能。(Windows7以降なら入っている)

image.png

ソースコード(1/2)

Replacer.cs
usingSystem;usingSystem.Drawing;usingSystem.Diagnostics;usingSystem.IO;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Runtime.InteropServices;usingSystem.Windows.Forms;classTextReplacer:Form{SplitContainerspl;TextBoxtxtPtrn;// for searchTextBoxtxtReplace;ButtonbtnFind;ButtonbtnReplace;ButtonbtnReplaceAll;CheckBoxchkRegex;CheckBoxchkSenseCase;MyRichTextBoxrtxt;ToolStripStatusLabelstatusLabel;staticreadonlyColordefaultBackColor=Color.White;FontbaseFont;stringcurFilePath;EncodingcurEnc;booleditFlag;TextReplacer(string[]args){curEnc=Encoding.UTF8;ClientSize=newSize(500,400);varmenuStrip1=newMenuStrip();SuspendLayout();menuStrip1.SuspendLayout();varfileMenuItem=newToolStripMenuItem(){Text="&File"};//var editMenuItem = new ToolStripMenuItem(){ Text = "&Edit"};menuStrip1.Items.Add(fileMenuItem);//menuStrip1.Items.Add(editMenuItem);fileMenuItem.DropDownItems.Add(newToolStripMenuItem("&Open...",null,(s,e)=>{OpenFileDialogWithEditingCheck();},Keys.Control|Keys.O));varfileMenuItemReopenEnc=newToolStripMenuItem("Reopen with encoding");fileMenuItem.DropDownItems.Add(fileMenuItemReopenEnc);fileMenuItemReopenEnc.DropDownItems.Add(newToolStripMenuItem("UTF8",null,(s,e)=>{ReopenWithEnc(Encoding.UTF8);},null));fileMenuItemReopenEnc.DropDownItems.Add(newToolStripMenuItem("Shift_JIS",null,(s,e)=>{ReopenWithEnc(Encoding.GetEncoding("Shift_JIS"));},null));//editMenuItem.DropDownItems.Add( new ToolStripMenuItem("&Find...", null, (s,e)=>{ShowFindDialog();}, Keys.Control | Keys.F) );Controls.Add(spl=newSplitContainer(){Dock=DockStyle.Fill,Orientation=Orientation.Horizontal,IsSplitterFixed=true,});LabellblSearch;spl.Panel1.Controls.AddRange(newControl[]{lblSearch=newLabel(){Text="Find",TextAlign=ContentAlignment.MiddleLeft,Location=newPoint(0,0),Size=newSize(50,25),},txtPtrn=newTextBox(){Multiline=false,Location=newPoint(50,0),Size=newSize(200,25),},btnFind=newButton(){Text="Find",Top=0,Size=newSize(100,25),},lblSearch=newLabel(){Text="Replace",TextAlign=ContentAlignment.MiddleLeft,Location=newPoint(0,25),Size=newSize(50,25),},txtReplace=newTextBox(){Multiline=false,Location=newPoint(50,25),Size=newSize(200,25),},btnReplace=newButton(){Text="Replace",Top=25,Size=newSize(100,25),},btnReplaceAll=newButton(){Text="ReplaceAll",Top=55,Size=newSize(100,25),},chkSenseCase=newCheckBox(){Text="大文字小文字を区別",Location=newPoint(50,50),Size=newSize(140,25),},chkRegex=newCheckBox(){Text="正規表現",Location=newPoint(50,75),Size=newSize(80,25),},});txtPtrn.TextChanged+=TxtPtrn_TextChanged;txtPtrn.KeyDown+=TxtPtrn_KeyDown;chkRegex.Click+=(s,e)=>{ReflectRegexValidityToControl();};btnFind.Click+=BtnFind_Click;btnReplace.Click+=BtnReplace_Click;btnReplaceAll.Click+=BtnReplaceAll_Click;spl.Panel2.Controls.Add(rtxt=newMyRichTextBox(){Multiline=true,WordWrap=false,AcceptsTab=true,ScrollBars=RichTextBoxScrollBars.Both,Dock=DockStyle.Fill,AllowDrop=true,HideSelection=false,});rtxt.DragEnter+=Rtxt_DragEnter;rtxt.DragDrop+=Rtxt_DragDrop;baseFont=newFont("MS ゴシック",10);// rtxt.Font.Size);rtxt.Font=baseFont;//rtxt.BackColor = Color.FromArgb(240,240,240);rtxt.TextChanged+=Rtxt_TextChanged;rtxt.SelectionChanged+=Rtxt_SelectionChanged;varstatusStrip=newStatusStrip();Controls.Add(statusStrip);statusStrip.Items.Add(statusLabel=newToolStripStatusLabel(){Text="",});// spl.IsSplitterFixed = true; はユーザがつかめないようにするだけで、固定してくれないっぽい。Load+=(sender,e)=>{MyResizeHandler();};Resize+=(sender,e)=>{MyResizeHandler();};ResizeEnd+=(sender,e)=>{MyResizeHandler();};Controls.Add(menuStrip1);MainMenuStrip=menuStrip1;menuStrip1.ResumeLayout(false);menuStrip1.PerformLayout();ResumeLayout(false);PerformLayout();if(args.Length==1){OpenFile(args[0],curEnc);}UpdateWindowTitle();}voidRtxt_SelectionChanged(objectsender,EventArgse){statusLabel.Text="L:"+(rtxt.GetLineFromCharIndex(rtxt.SelectionStart)+1).ToString();}voidMyResizeHandler(){intw=ClientSize.Width-txtPtrn.Left-btnFind.Width;if(w<10){w=10;}intsplDistanceTarget=chkRegex.Bottom;try{spl.SplitterDistance=splDistanceTarget;}catch(InvalidOperationException){// ignore}txtPtrn.Width=w;txtReplace.Width=w;btnFind.Left=txtPtrn.Right;btnReplace.Left=txtReplace.Right;btnReplaceAll.Left=txtReplace.Right;}voidTxtPtrn_TextChanged(objectsender,EventArgse){ReflectRegexValidityToControl();}voidTxtPtrn_KeyDown(objectsender,KeyEventArgse){if(e.KeyData==Keys.Enter){FindNext();}}voidBtnReplaceAll_Click(objectsender,EventArgse){Regexr=TryNewRegex();if(r!=null){strings=rtxt.Text;stringafterS=txtReplace.Text;strings2=r.Replace(s,afterS);rtxt.Text=s2;}}voidBtnReplace_Click(objectsender,EventArgse){ReplaceCurrent();FindNext();}voidBtnFind_Click(objectsender,EventArgse){FindNext();}voidFindNext(){Regexr=TryNewRegex();if(r!=null){strings=rtxt.Text;intsearchStartI;if(rtxt.SelectionLength==s.Length){searchStartI=0;}elseif(rtxt.SelectionLength==0){searchStartI=rtxt.SelectionStart+1;}else{searchStartI=rtxt.SelectionStart+rtxt.SelectionLength;}if(searchStartI<=s.Length){Matchm=r.Match(s,searchStartI);if(m.Success){rtxt.Select(m.Index,m.Length);}else{statusLabel.Text="Not found.";}}}}voidReplaceCurrent(){strings=rtxt.Text;if(rtxt.SelectionLength!=s.Length){inti=rtxt.SelectionStart;intlen=rtxt.SelectionLength;rtxt.SelectedText=txtReplace.Text;}}voidRtxt_TextChanged(objectsender,EventArgse){editFlag=true;UpdateWindowTitle();}voidReflectRegexValidityToControl(){if(TryNewRegex()!=null){txtPtrn.BackColor=defaultBackColor;}else{txtPtrn.BackColor=Color.FromArgb(0xFF,0xDD,0xDD);}}RegexTryNewRegex(){RegexOptionsropt=(chkSenseCase.Checked)?RegexOptions.None:RegexOptions.IgnoreCase;try{if(chkRegex.Checked){returnnewRegex(txtPtrn.Text,ropt);}else{returnnewRegex(Regex.Escape(txtPtrn.Text),ropt);}}catch(ArgumentException){}returnnull;}voidUpdateWindowTitle(){strings=curFilePath??"Untitled";stringdirtyMark=editFlag?" (*)":"";Text=s+dirtyMark+" - Replacer";}voidRtxt_DragEnter(objectsender,DragEventArgse){if(e.Data.GetDataPresent(DataFormats.FileDrop)){e.Effect=DragDropEffects.Copy;}else{e.Effect=DragDropEffects.None;}}voidRtxt_DragDrop(objectsender,DragEventArgse){if(e.Data.GetDataPresent(DataFormats.FileDrop)){string[]fileNames;fileNames=(string[])e.Data.GetData(DataFormats.FileDrop,false);if(fileNames.Length==1){OpenFileWithEditingCheck(fileNames[0],curEnc);}}}boolGetDiscurdDialogResultWhenEditing(){if(editFlag){DialogResultret=MessageBox.Show("Are you O.K. to discard current text.","Confirmation",MessageBoxButtons.OKCancel);if(ret!=DialogResult.OK){returnfalse;}}returntrue;}boolOpenFileWithEditingCheck(stringfileName,Encodingenc){if(!GetDiscurdDialogResultWhenEditing()){returnfalse;}returnOpenFile(fileName,enc);}boolOpenFile(stringfileName,Encodingenc){stringtmpPath=Path.GetFullPath(fileName);Text=Path.GetFileName(tmpPath);try{rtxt.Text=File.ReadAllText(tmpPath,enc);}catch(IOExceptione){MessageBox.Show(e.ToString());returnfalse;}editFlag=false;curFilePath=tmpPath;UpdateWindowTitle();returntrue;}boolReopenWithEnc(Encodingenc){if(curFilePath!=null){curEnc=enc;returnOpenFileWithEditingCheck(curFilePath,enc);}else{curEnc=enc;returnfalse;}}boolOpenFileDialogWithEditingCheck(){if(!GetDiscurdDialogResultWhenEditing()){returnfalse;}OpenFileDialogofd=newOpenFileDialog();ofd.FileName="テンプレート.xml";ofd.Filter="Text file|*.txt;*.log;*.csv;*.xml;*.htm;*.html;*.adoc;*.bat;*.ps;*.c;*.h;*.asm;*.ld;*.map;*.mot;*.js;*.cs;*.bas;*.java;*.rb;*.py|All file(*.*)|*.*";ofd.RestoreDirectory=true;if(ofd.ShowDialog()==DialogResult.OK){returnOpenFile(ofd.FileName,curEnc);}returnfalse;}[STAThread]publicstaticvoidMain(string[]args){Application.Run(newTextReplacer(args));}}

ソースコード(2/2)

MyRichTextBox.cs
usingSystem;usingSystem.Drawing;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Runtime.InteropServices;usingSystem.Windows.Forms;internalclassMyRichTextBox:RichTextBox{//----------------------------------------------------------------// Win32//privateconstintEM_SETTABSTOPS=0x00CB;privateconstlongIMF_DUALFONT=0x80;privateconstintWM_SETREDRAW=0x0008;privateconstintWM_USER=0x0400;privateconstintEM_SETLANGOPTIONS=WM_USER+120;privateconstintEM_GETLANGOPTIONS=WM_USER+121;privateconstintEM_GETTEXTEX=(WM_USER+94);privateconstintEM_GETTEXTLENGTHEX=(WM_USER+95);// Flags for the GETEXTEX data structure  privateconstintGT_DEFAULT=0;privateconstintGTL_CLOSE=4;// Fast computation of a "close" answer privateconstintGTL_DEFAULT=0;// Do default (return # of chars) classNativeMethods{[DllImport("user32.dll",EntryPoint="SendMessage",CharSet=CharSet.Auto)]publicexternstaticIntPtrSendMessage(IntPtrhWnd,intMsg,IntPtrwParam,IntPtrlParam);[DllImport("user32.dll",EntryPoint="SendMessage",CharSet=CharSet.Auto)]publicstaticexternIntPtrSendMessage(IntPtrhWnd,intmsg,refGETTEXTEXwParam,StringBuilderlParam);[DllImport("user32.dll",EntryPoint="SendMessage",CharSet=CharSet.Auto)]publicstaticexternIntPtrSendMessage(IntPtrhWnd,intmsg,refGETTEXTLENGTHEXwParam,IntPtrlParam);}[StructLayout(LayoutKind.Sequential)]structGETTEXTEX{publicintcb;publicintflags;publicintcodepage;publicIntPtrlpDefaultChar;publicIntPtrlpUsedDefChar;}[StructLayout(LayoutKind.Sequential)]structGETTEXTLENGTHEX{publicintflags;publicintcodepage;}////----------------------------------------------------------------protectedoverridevoidOnFontChanged(EventArgse){SetFixFont();SetTabStop(4);}publicoverridestringText{get{vargetLength=newGETTEXTLENGTHEX();getLength.flags=GTL_CLOSE;//get buffer sizegetLength.codepage=1200;//UnicodeinttextLength=(int)(NativeMethods.SendMessage(this.Handle,EM_GETTEXTLENGTHEX,refgetLength,IntPtr.Zero).ToInt64());vargetText=newGETTEXTEX();getText.cb=textLength+2;//add space for null terminatorif(getText.cb<2){return"";}// overflowgetText.flags=GT_DEFAULT;getText.codepage=1200;//Unicodevarsb=newStringBuilder(getText.cb);NativeMethods.SendMessage(this.Handle,EM_GETTEXTEX,refgetText,sb);returnsb.ToString();}set{base.Text=value;}}publicoverrideintTextLength{get{vargetLength=newGETTEXTLENGTHEX();getLength.flags=GTL_DEFAULT;//Returns the number of charactersgetLength.codepage=1200;//UnicodeinttextLength=(int)(NativeMethods.SendMessage(this.Handle,EM_GETTEXTLENGTHEX,refgetLength,IntPtr.Zero).ToInt64());if(textLength<0){return0;}// overflowreturntextLength;}}privatevoidSetFixFont(){IntPtrlParam=NativeMethods.SendMessage(this.Handle,EM_GETLANGOPTIONS,newIntPtr(0),newIntPtr(0));lParam=newIntPtr(((long)lParam)&(~IMF_DUALFONT));NativeMethods.SendMessage(this.Handle,EM_SETLANGOPTIONS,newIntPtr(0),lParam);}privatevoidSetTabStop(inttabSize){int[]tabarray=newint[]{tabSize*4};intwparam=tabarray.Length;IntPtrparray=Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int))*tabarray.Length);Marshal.Copy(tabarray,0,parray,tabarray.Length);NativeMethods.SendMessage(this.Handle,EM_SETTABSTOPS,newIntPtr(wparam),parray);}}

Viewing all articles
Browse latest Browse all 9374

Latest Images

Trending Articles