Board logo

标题: [原创]发个CMD下正则替换工具(js正则引擎) [打印本页]

作者: freeants001     时间: 2010-8-3 14:23    标题: [原创]发个CMD下正则替换工具(js正则引擎)

由于个人习惯JS正则,所以用AHK封装成EXE,以便在命令行下使用。
下载地址:http://rthost.fam.cx/cndos-up/img/1902.zip

使用说明:
    regex 有四个参,
  第一个为待处理的文件。
  第二个为JS正则表达式。 即stringObj.replace(rgExp, replaceText)中的红色部分
  第三个为 替换字符串。 即stringObj.replace(rgExp, replaceText)中的红色部分
  第四个参数可选,为U或Unicode,表示处处理后文本保存为Unicode。如果省略此参数,处理结果优先保存为Ansi。


1、替换文本文件中的FOX(不区分大小写)单词为DOG单词
CODE:  [Copy to clipboard]
regex  textfile.txt   "/\bfox\b/gi"   "DOG"
2、批量处理当前目录下文本文件,删除每行开始的空白
CODE:  [Copy to clipboard]
regex   *.txt   "/^[ \t]+/gm"   ""
3、删除文本文件中所有Begin:开始的行到End:结束的行
CODE:  [Copy to clipboard]
regex   textfile.txt   "/(^|\r\n)Begin:\r\n(.*\r\n)*End:\r\n/g"   "\r\n"
4、在文件A.TXT中的每个汉字后插入一个空格,结果保存为Unicode格式
CODE:  [Copy to clipboard]
regex   a.txt  "/([\u4E00-\u9FCF])/g"  "$1 "  Unicode
详细的请查阅JS正则

[ Last edited by freeants001 on 2010-8-3 at 15:14 ]
作者: swing     时间: 2010-8-9 23:13    标题: Excellent!

贴个源代码出来就更好了.
作者: freeants001     时间: 2010-8-11 18:50
代码:
CODE:  [Copy to clipboard]
#NoEnv
#SingleInstance force
#Include ws4ahk.ahk

SetBatchLines -1
WS_Initialize("jscript")

loop,%1%
{
        __FILE:=A_LoopFileLongPath
        StringReplace, __FILE, __FILE, \ , \\, All
        Code=
        (LTrim
        fso=new ActiveXObject("Scripting.FileSystemObject");
        try{
                var ts=fso.opentextfile("%__FILE%",1,false,-2);
                var sss=ts.readall();
                ts.close();
        }catch(err){
                WScript.quit();
        }

        if(/^LTrim$/i.test("%2%"))sss=sss.replace(/^[ \t]+/mg,'');
        else if(/^RTrim$/i.test("%2%"))sss=sss.replace(/[ \t]+$/mg,'');
        else if(/^Trim$/i.test("%2%")){
                sss=sss.replace(/^[ \t]+/mg,'');
                sss=sss.replace(/[ \t]+$/mg,'');
        } else {
                  sss=sss.replace(%2%,"%3%");
        }

        if (/^U(nicode)?$/i.test("%4%"))
        {
                try{saveTextAsUnicode(sss,"%__FILE%");}catch(err){}
        } else {
                try{// try to saving as Ansi
                        saveTextAsAnsi(sss,"%__FILE%");
                }catch(err){// save as Unicode
                        saveTextAsUnicode(sss,"%__FILE%");
                }
        }

        function saveTextAsAnsi(sss,fname)
        {
                ts=fso.opentextfile(fname,2,true,0);
                ts.write(sss);
                ts.close();
        }

        function saveTextAsUnicode(sss,fname)
        {
                ts.close();
                ts=fso.opentextfile(fname,2,true,-1);
                ts.write(sss);
                ts.close();
        }
        )
        ws_exec(code)
}
WS_Uninitialize()
[ Last edited by freeants001 on 2010-8-11 at 19:33 ]




欢迎光临 中国DOS联盟论坛 (http://cndos.fam.cx/forum/) Powered by Discuz! 2.5