[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

JScript实现的批处理正则表达式库 JREPL

本帖最后由 codegay 于 2016-3-27 21:14 编辑

在这里看到的:
http://stackoverflow.com/questio ... ms-dos-command-line

代码出处,使用方法看这里 http://www.dostips.com/forum/viewtopic.php?t=6044
  1. @if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment
  2. @goto :Batch
  3. ::JREPL.BAT version 3.7 by Dave Benham
  4. ::
  5. ::  Release History:
  6. ::    2016-01-14 v3.7: Reworked error handling a bit.
  7. ::                     Bug fix - \xnn and \unnnn could fail in a regex search
  8. ::                     if result was a meta-character and /X option was used.
  9. ::    2015-07-15 v3.6: Added /?? option for paged help.
  10. ::    2015-06-12 v3.5: Bug fix for $n or $nn in replace string when /T is
  11. ::                     used without /J or /JMATCH or /L
  12. ::    2015-01-22 v3.4: Bug fix - Use /TEST instead of TEST as a variable name
  13. ::                     within the option parser so that it is unlikely to
  14. ::                     collide with a user defined variable name.
  15. ::    2014-12-24 v3.3: Bug fix for when /JMATCH is combined with /M or /S
  16. ::    2014-12-09 v3.2: Bug fix for /T without /JMATCH - fixed dynamic repl func
  17. ::                     Added GOTO at top for improved startup performance
  18. ::    2014-11-25 v3.1: Added /JLIB option
  19. ::                     Exception handler reports when regex is bad
  20. ::                     Fix /X bug with extended ASCII
  21. ::    2014-11-23 v3.0: Added /JBEGLN and /JENDLN options
  22. ::                     Added skip, quit, and lpad() global variables/functions
  23. ::                     Exception handler reports when error in user code
  24. ::    2014-11-21 v2.2: Bug fix for /T with /L option.
  25. ::    2014-11-20 v2.1: Bug fix for /T option when match is an empty string
  26. ::    2014-11-17 v2.0: Added /T (translate) and /C (count input lines) options
  27. ::    2014-11-14 v1.0: Initial release
  28. ::
  29. ::============ Documentation ===========
  30. :::
  31. :::JREPL  Search  Replace  [/Option  [Value]]...
  32. :::JREPL  /?[REGEX|REPLACE|VERSION]
  33. :::JREPL  /??
  34. :::
  35. :::  Performs a global regular expression search and replace operation on
  36. :::  each line of input from stdin and prints the result to stdout.
  37. :::
  38. :::  Each parameter may be optionally enclosed by double quotes. The double
  39. :::  quotes are not considered part of the argument. The quotes are required
  40. :::  if the parameter contains a batch token delimiter like space, tab, comma,
  41. :::  semicolon. The quotes should also be used if the argument contains a
  42. :::  batch special character like &, |, etc. so that the special character
  43. :::  does not need to be escaped with ^.
  44. :::
  45. :::  Search  - By default, this is a case sensitive JScript (ECMA) regular
  46. :::            expression expressed as a string.
  47. :::
  48. :::            JScript regex syntax documentation is available at
  49. :::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
  50. :::
  51. :::  Replace - By default, this is the string to be used as a replacement for
  52. :::            each found search expression. Full support is provided for
  53. :::            substituion patterns available to the JScript replace method.
  54. :::
  55. :::            For example, $& represents the portion of the source that matched
  56. :::            the entire search pattern, $1 represents the first captured
  57. :::            submatch, $2 the second captured submatch, etc. A $ literal
  58. :::            can be escaped as $$.
  59. :::
  60. :::            An empty replacement string must be represented as "".
  61. :::
  62. :::            Replace substitution pattern syntax is fully documented at
  63. :::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
  64. :::
  65. :::  Options:  Behavior may be altered by appending one or more options.
  66. :::  The option names are case insensitive, and may appear in any order
  67. :::  after the Replace argument.
  68. :::
  69. :::      /A  - Only print altered lines. Unaltered lines are discarded.
  70. :::            If the /S option is used, then prints the result only if
  71. :::            there was a change anywhere in the string. The /A option
  72. :::            is incompatible with the /M option unless the /S option
  73. :::            is also present.
  74. :::
  75. :::      /B  - The Search must match the beginning of a line.
  76. :::            Mostly used with literal searches.
  77. :::
  78. :::      /C  - Count the number of input lines and store the result in global
  79. :::            variable cnt. This value can be useful in JScript code associated
  80. :::            with any of the /Jxxx options.
  81. :::
  82. :::            This option is incompatible with the /M and /S options.
  83. :::
  84. :::            If the input data is piped or redirected, then the data is first
  85. :::            written to a temporary file, so processing does not start until
  86. :::            the end-of-file is reached.
  87. :::
  88. :::      /E  - The Search must match the end of a line.
  89. :::            Mostly used with literal searches.
  90. :::
  91. :::      /F InFile
  92. :::
  93. :::            Input is read from file InFile instead of stdin.
  94. :::
  95. :::      /I  - Makes the search case-insensitive.
  96. :::
  97. :::      /J  - The Replace argument is a JScript expression.
  98. :::            The following variables contain details about each match:
  99. :::
  100. :::              $0 is the substring that matched the Search
  101. :::              $1 through $n are the captured submatch strings
  102. :::              $off is the offset where the match occurred
  103. :::              $src is the original source string
  104. :::
  105. :::      /JBEG InitCode
  106. :::
  107. :::            JScript inititialization code to run prior to loading any input.
  108. :::            This is useful for initializing user defined variables for
  109. :::            accumulating information across matches. The default code is an
  110. :::            empty string.
  111. :::
  112. :::      /JBEGLN NewLineCode
  113. :::
  114. :::            JScript code to run at the beginning of each line, prior to
  115. :::            performing any matching on the line. The line content may be
  116. :::            manipulated via the $txt variable. The default code is an empty
  117. :::            string. This option is incompatible with the /M and /S options.
  118. :::
  119. :::      /JEND FinalCode
  120. :::
  121. :::            JScript termination code to run when there is no more input to
  122. :::            read. This is useful for writing summarization results.
  123. :::            The default code is an empty string.
  124. :::
  125. :::      /JENDLN EndLineCode
  126. :::
  127. :::            JScript code to run at the end of each line, after all matches
  128. :::            on the line have been found, but before the result is printed.
  129. :::            The final result can be modified via the $txt variable. Setting
  130. :::            $txt to false discards the line without printing. The $txt value
  131. :::            is ignored if the /JMATCH option has been used. The default
  132. :::            code is an empty string. This option is incompatible with the
  133. :::            /M and /S options.
  134. :::
  135. :::      /JLIB FileList
  136. :::
  137. :::            Specifies one or more files that contain libraries of JScript
  138. :::            code to load before /JBEG is run. Multiple files are delimited
  139. :::            by forward slashes (/). Useful for declaring global variables
  140. :::            and functions in a way that is reusable.
  141. :::
  142. :::      /JMATCH
  143. :::
  144. :::            Prints each Replace value on a new line, discarding all text
  145. :::            that does not match the Search. The Replace argument is a
  146. :::            JScript expression with access to the same $ variables available
  147. :::            to the /J option. Replacement values that evaluate to false
  148. :::            are discarded.
  149. :::
  150. :::      /L  - The Search is treated as a string literal instead of a
  151. :::            regular expression. Also, all $ found in the Replace string
  152. :::            are treated as $ literals.
  153. :::
  154. :::      /M  - Multi-line mode. The entire input is read and processed in one
  155. :::            pass instead of line by line, thus enabling search for \n. This
  156. :::            also enables preservation of the original line terminators.
  157. :::            If the /M option is not present, then every printed line is
  158. :::            terminated with carriage return and line feed. The /M option is
  159. :::            incompatible with the /A option unless the /S option is also
  160. :::            present.
  161. :::
  162. :::            Note: If working with binary data containing NULL bytes,
  163. :::                  then the /M option must be used.
  164. :::
  165. :::      /N MinWidth
  166. :::
  167. :::            Precede each output line with the line number of the source line,
  168. :::            followed by a colon. Line 1 is the first line of the source.
  169. :::
  170. :::            The MinWidth value specifies the minimum number of digits to
  171. :::            display. The default value is 0, meaning do not display the
  172. :::            line number. A value of 1 diplays the line numbers without any
  173. :::            zero padding.
  174. :::
  175. :::            The /N option is ignored if the /M or /S option is used.
  176. :::
  177. :::      /O OutFile
  178. :::
  179. :::            Output is written to file OutFile instead of stdout.
  180. :::
  181. :::            A value of "-" replaces the InFile with the output. The output
  182. :::            is first written to a temporary file with the same name as InFile
  183. :::            with .new appended. Upon completion, the temporary file is moved
  184. :::            to replace the InFile.
  185. :::
  186. :::      /OFF MinWidth
  187. :::
  188. :::            Ignored unless the /JMATCH option is used. Precede each output
  189. :::            line with the offset of the match within the original source
  190. :::            string, followed by a colon. Offset 0 is the first character of
  191. :::            the source string. The offset follows the line number if the /N
  192. :::            option is also used.
  193. :::
  194. :::            The MinWidth value specifies the minimum number of digits to
  195. :::            display. The default value is 0, meaning do not display the
  196. :::            offset. A value of 1 displays the offsets without any zero
  197. :::            padding.
  198. :::
  199. :::      /S VarName
  200. :::
  201. :::            The source is read from environment variable VarName instead
  202. :::            of from stdin. Without the /M option, ^ anchors the beginning
  203. :::            of the string, and $ the end of the string. With the /M option,
  204. :::            ^ anchors the beginning of a line, and $ the end of a line.
  205. :::
  206. :::            The variable name cannot match any of the option names, nor can
  207. :::            it be /TEST. Put another way, any variable can be used as long as
  208. :::            the name does not begin with a forward slash.
  209. :::
  210. :::      /T DelimiterChar
  211. :::
  212. :::            The /T option is very similar to the Oracle Translate() function,
  213. :::            or the unix tr command, or the sed y command.
  214. :::
  215. :::            The Source represents a set of search expressions, and Replace
  216. :::            is a like sized set of replacement expressions. Expressions are
  217. :::            delimited by DelimiterChar (a single character). If DelimiterChar
  218. :::            is an empty string, then each character is treated as its own
  219. :::            expression. The /L option is implicitly set if DelimiterChar is
  220. :::            empty. Escape sequences are interpreted after the search and
  221. :::            replace strings are split into expressions, so escape sequences
  222. :::            cannot be used without a delimiter.
  223. :::
  224. :::            Each substring from the input that matches a particular search
  225. :::            expression is translated into the corresponding replacement
  226. :::            expression.
  227. :::
  228. :::            The search expressions may be regular expressions, possibly with
  229. :::            captured subexpression. Note that each expression is itself
  230. :::            converted into a captured subexpression and the operation is
  231. :::            performed as a single search/replace upon execution. So
  232. :::            backreferences within each regex and $n references within each
  233. :::            replacement expression must be adjusted accordingly.
  234. :::
  235. :::            The total number of expressions plus captured subexpressions must
  236. :::            not exceed 99.
  237. :::
  238. :::            If an expression must include a delimiter, then an escape
  239. :::            sequence must be used.
  240. :::
  241. :::            Search expressions are tested from left to right. The left most
  242. :::            matching expression takes precedence when there are multiple
  243. :::            matching expressions.
  244. :::
  245. :::      /V  - Search, Replace, /JBEG InitCode, /JBEGLN NewLineCode, /JEND
  246. :::            FinalCode, and /JENDLN EndLineCode all represent the names
  247. :::            of environment variables that contain the respective values.
  248. :::            An undefined variable is treated as an empty string.
  249. :::
  250. :::            The variable names must not match any of the option names, nor
  251. :::            can they be /TEST.
  252. :::
  253. :::      /X  - Enables extended substitution pattern syntax with support
  254. :::            for the following escape sequences within the Replace string:
  255. :::
  256. :::            \\     -  Backslash
  257. :::            \b     -  Backspace
  258. :::            \f     -  Formfeed
  259. :::            \n     -  Newline
  260. :::            \q     -  Quote
  261. :::            \r     -  Carriage Return
  262. :::            \t     -  Horizontal Tab
  263. :::            \v     -  Vertical Tab
  264. :::            \xnn   -  ASCII byte code expressed as 2 hex digits
  265. :::            \unnnn -  Unicode character expressed as 4 hex digits
  266. :::
  267. :::            Also enables the \q escape sequence for the Search string.
  268. :::            The other escape sequences are already standard for a regular
  269. :::            expression Search string.
  270. :::
  271. :::            Also modifies the behavior of \xnn in the Search string to work
  272. :::            properly with extended ASCII byte codes (values above 0x7F).
  273. :::
  274. :::            Extended escape sequences are supported even when the /L option
  275. :::            is used. Both Search and Replace support all of the extended
  276. :::            escape sequences if both the /X and /L opions are combined.
  277. :::
  278. :::            Extended escape sequences are not applied to JScript code when
  279. :::            using any of the /Jxxx options. Use the decode() function if
  280. :::            extended escape sequences are needed within the code.
  281. :::
  282. :::  The following global JScript variables/objects/functions are available for
  283. :::  use in JScript code associated with the /Jxxx options. User code may safely
  284. :::  declare additional variables/objects/functions because all other internal
  285. :::  objects used by JREPL are hidden behind an opaque _g object.
  286. :::
  287. :::      ln     - Within /JBEGLN, /JENDLN, and Replace code = current line number
  288. :::               Within /JBEG code = 0
  289. :::               Within /JEND code = total number of lines read.
  290. :::               This value is always 0 if the /M or /S option is used.
  291. :::
  292. :::      cnt    - The total number of lines in the input. The value is undefined
  293. :::               unless the /C option is used.
  294. :::
  295. :::      skip   - If true, do not search/replace any more lines until the value
  296. :::               becomes false. /JBEGLN and /JENDLN code are still executed for
  297. :::               each line, regardless. If set to true while in the midst of
  298. :::               searching a line, then that search will continue to the end of
  299. :::               the current line.
  300. :::
  301. :::               The default value is false.
  302. :::
  303. :::               This variable has no impact if the /M or /S options is used.
  304. :::
  305. :::      quit   - If true, then do not read any more lines of input. The current
  306. :::               line is still processed to completion, and /JEND code is still
  307. :::               executed afterward.
  308. :::
  309. :::               The default value is false.
  310. :::
  311. :::               This variable has no impact if the /M or /S options is used.
  312. :::
  313. :::      env('varName')
  314. :::
  315. :::               Access to environment variable named varName.
  316. :::
  317. :::      decode(string)
  318. :::
  319. :::               Decodes extended escape sequences within a string as defined
  320. :::               by the /X option, and returns the result. All backslashes must
  321. :::               be escaped an extra time to use this function in your code.
  322. :::
  323. :::               Examples:
  324. :::                  quote literal:       decode('\\q')
  325. :::                  extended ASCII(128): decode('\\x80')
  326. :::                  backslash literal:   decode('\\\\')
  327. :::
  328. :::               This function is only needed if you use the \q sequence
  329. :::               or \xnn for an extended ASCII code (values above 0x7F).
  330. :::
  331. :::      lpad(value,pad)
  332. :::
  333. :::               Used to left pad a value to a minimum width string. If the
  334. :::               value already has string width >= the pad length, then no
  335. :::               change is made. Otherwise it left pads the value with the
  336. :::               characters of the pad string to the width of the pad string.
  337. :::
  338. :::               Examples:
  339. :::                  lpad(15,'0000')    returns "0015"
  340. :::                  lpad(15,'    ')    returns "  15"
  341. :::                  lpad(19011,'0000') returns "19011"
  342. :::
  343. :::      input  - The TextStream object from which input is read.
  344. :::               This may be stdin or a file.
  345. :::
  346. :::      output - The TextStream object to which the output is written.
  347. :::               This may be stdout or a file.
  348. :::
  349. :::      stdin  - Equivalent to WScript.StdIn
  350. :::
  351. :::      stdout - Equivalent to WScript.StdOut
  352. :::
  353. :::      stderr - Equivalent to WScript.StdErr
  354. :::
  355. :::  Help is available by supplying a single argument beginning with /?:
  356. :::
  357. :::      /?        - Writes this help documentation to stdout.
  358. :::      /??       - Same as /? except uses MORE for pagination
  359. :::
  360. :::      /?REGEX   - Opens up Microsoft's JScript regular expression
  361. :::                  documentation within your browser.
  362. :::
  363. :::      /?REPLACE - Opens up Microsoft's JScript REPLACE documentation
  364. :::                  within your browser.
  365. :::
  366. :::      /?VERSION - Writes the JREPL version number to stdout.
  367. :::
  368. :::  Return Codes:
  369. :::
  370. :::      0 = At least one change was made and /JMATCH not used
  371. :::          or at least one match returned and /JMATCH was used
  372. :::          or /? was used
  373. :::
  374. :::      1 = No change was made and /JMATCH not used
  375. :::          or no match returned and /JMATCH was used
  376. :::
  377. :::      2 = Invalid call syntax or incompatible options
  378. :::
  379. :::      3 = JScript runtime error
  380. :::
  381. :::  JREPL.BAT was written by Dave Benham, and originally posted at
  382. :::  http://www.dostips.com/forum/viewtopic.php?f=3&t=6044
  383. :::
  384. ============= :Batch portion ===========
  385. @echo off
  386. setlocal disableDelayedExpansion
  387. if .%2 equ . (
  388.   if "%~1" equ "/?" (
  389.     for /f "tokens=* delims=:" %%A in ('findstr "^:::" "%~f0"') do @echo(%%A
  390.     exit /b 0
  391.   ) else if "%~1" equ "/??" 2>nul (
  392.     (for /f "tokens=* delims=:" %%A in ('findstr "^:::" "%~f0"') do @echo(%%A)|more /e
  393.     exit /b 0
  394.   ) else if /i "%~1" equ "/?regex" (
  395.     explorer "http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx"
  396.     exit /b 0
  397.   ) else if /i "%~1" equ "/?replace" (
  398.     explorer "http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx"
  399.     exit /b 0
  400.   ) else if /i "%~1" equ "/?version" (
  401.     for /f "tokens=* delims=:" %%A in ('findstr "^::JREPL\.BAT" "%~f0"') do @echo(%%A
  402.     exit /b 0
  403.   ) else call :exitErr "Insufficient arguments"
  404. )
  405. :: Define options
  406. set "options= /A: /B: /C: /E: /F:"" /I: /J: /JBEG:"" /JBEGLN:"" /JEND:"" /JENDLN:"" /JLIB:"" /JMATCH: /L: /M: /N:0 /O:"" /OFF:0 /S:"" /T:"none" /V: /X: "
  407. :: Set default option values
  408. for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
  409. :: Get options
  410. :loop
  411. if not "%~3"=="" (
  412.   set "/test=%~3"
  413.   setlocal enableDelayedExpansion
  414.   if "!/test:~0,1!" neq "/" call :exitErr "Too many arguments"
  415.   set "/test=!options:*%~3:=! "
  416.   if "!/test!"=="!options! " (
  417.       endlocal
  418.       call :exitErr "Invalid option %~3"
  419.   ) else if "!/test:~0,1!"==" " (
  420.       endlocal
  421.       set "%~3=1"
  422.   ) else (
  423.       endlocal
  424.       set "%~3=%~4"
  425.       shift /3
  426.   )
  427.   shift /3
  428.   goto :loop
  429. )
  430. :: Validate options
  431. if defined /M if defined /A if not defined /S                                      call :exitErr "/M cannot be used with /A without /S"
  432. if "%/O%" equ "-" if not defined /F                                                call :exitErr "Output = - but Input file not specified"
  433. if defined /F for %%A in ("%/F%") do for %%B in ("%/O%") do if "%%~fA" equ "%%~fB" call :exitErr "Output file cannot match Input file"
  434. if "%/C%%/JBEGLN%%/JENDLN%" neq "" if "%/M%%/S%" neq ""                            call :exitErr "/C, /JBEGLN, and /JENDLN cannot be used with /M or /S"
  435. :: Transform options
  436. if defined /JMATCH set "/J=1"
  437. if "%/M%%/S%" neq "" set "/N=0"
  438. :: Execute
  439. cscript //E:JScript //nologo "%~f0" %1 %2
  440. exit /b %errorlevel%
  441. :exitErr
  442. >&2 (
  443.   echo ERROR: %~1.
  444.   echo   Use JREPL /? or JREPL /?? to get help.
  445.   (goto) 2>nul
  446.   exit /b 2
  447. )
  448. ************* JScript portion **********/
  449. var _g=new Object();
  450. _g.loc='';
  451. try {
  452.   var env=WScript.CreateObject("WScript.Shell").Environment("Process"),
  453.       cnt,
  454.       ln=0,
  455.       skip=false,
  456.       quit=false,
  457.       stdin=WScript.StdIn,
  458.       stdout=WScript.Stdout,
  459.       stderr=WScript.Stderr,
  460.       output,
  461.       input;
  462.   _g.ForReading=1;
  463.   _g.ForWriting=2;
  464.   _g.TemporaryFolder=2;
  465.   _g.fso = new ActiveXObject("Scripting.FileSystemObject");
  466.   _g.inFile=env('/F');
  467.   _g.outFile=env('/O');
  468.   _g.tempFile='';
  469.   if (_g.inFile=='') {
  470.     if (env('/C')) {
  471.       _g.tempFile=_g.fso.GetSpecialFolder(_g.TemporaryFolder).path+'\\'+_g.fso.GetTempName();
  472.       _g.inFile=_g.tempFile;
  473.       input=stdin;
  474.       output=_g.fso.OpenTextFile(_g.tempFile,_g.ForWriting,true);
  475.       while (!stdin.AtEndOfStream) output.WriteLine(input.ReadLine());
  476.       cnt=input.line-1;
  477.       output.close();
  478.       input=_g.fso.OpenTextFile(_g.tempFile,_g.ForReading);
  479.     } else input=stdin;
  480.   } else {
  481.     if (env('/C')) {
  482.       input=_g.fso.OpenTextFile(_g.inFile,_g.ForReading);
  483.       while (!input.AtEndOfStream) input.SkipLine();
  484.       cnt=input.line-1;
  485.       input.close();
  486.     }
  487.     input=_g.fso.OpenTextFile(_g.inFile,_g.ForReading);
  488.   }
  489.   if (_g.outFile=='') {
  490.     output=stdout
  491.   } else if (_g.outFile=='-') {
  492.     output=_g.fso.OpenTextFile(_g.inFile+'.new',_g.ForWriting,true);
  493.   } else {
  494.     output=_g.fso.OpenTextFile(_g.outFile,_g.ForWriting,true);
  495.   }
  496.   if (env('/JLIB')) {
  497.     _g.loc=' while loading /JLIB code';
  498.     var libs=env('/JLIB').split('/');
  499.     for (var i=0; i<libs.length; i++) {
  500.       var lib=_g.fso.OpenTextFile(libs[i],_g.ForReading);
  501.       if (!lib.AtEndOfStream) eval(lib.ReadAll());
  502.       lib.close();
  503.     }
  504.     _g.loc='';
  505.   }
  506.    _g.loc=' in /JBEG code';
  507.   eval(env( env('/V') ? env('/JBEG') : '/JBEG' ));
  508.   _g.loc='';
  509.   _g.fmtNum=function(val,pad){return pad.length==0 ? '' : lpad(val,pad)+':';}
  510.   _g.writeMatch=function(str,off,lnPad,offPad) {
  511.     if (str!==false) {
  512.       _g.rtn=0;
  513.       output.WriteLine(_g.fmtNum(ln,lnPad)+_g.fmtNum(off,offPad)+str);
  514.     }
  515.   }
  516.   _g.defineReplFunc=function() {
  517.     eval(_g.replFunc);
  518.   }
  519.   _g.callBeginLine=function($txt) {
  520.     _g.loc=' in /JBEGLN code'
  521.     eval(_g.begLn);
  522.     _g.loc='';
  523.     return $txt;
  524.   }
  525.   _g.callEndLine=function($txt) {
  526.     _g.loc=' in /JENDLN code';
  527.     eval(_g.endLn);
  528.     _g.loc='';
  529.     return $txt;
  530.   }
  531.   _g.main=function() {
  532.     _g.rtn=1;
  533.     var args=WScript.Arguments;
  534.     var search=args.Item(0);
  535.     var replace=args.Item(1);
  536.     var options="g";
  537.     var multi=env('/M')!='';
  538.     var literal=env('/L')!='';
  539.     var alterations=env('/A')!='';
  540.     var srcVar=env('/S');
  541.     var jexpr=env('/J')!='';
  542.     var jmatch=env('/JMATCH')!='';
  543.     var translate=env('/T');
  544.     _g.begLn=env('/JBEGLN');
  545.     _g.endLn=env('/JENDLN');
  546.     if (multi) options+='m';
  547.     if (env('/V')) {
  548.       search=env(search);
  549.       replace=env(replace);
  550.       _g.begLn=env(_g.begLn);
  551.       _g.endLn=env(_g.endLn);
  552.     }
  553.     if (env('/I')) options+='i';
  554.     var lnWidth=parseInt(env('/N'),10),
  555.         offWidth=parseInt(env('/OFF'),10),
  556.         lnPad=lnWidth>0?Array(lnWidth+1).join('0'):'',
  557.         offPad=offWidth>0?Array(offWidth+1).join('0'):'',
  558.         xcnt=0, test;
  559.     if (translate=='none') {  // Normal
  560.       if (env('/X')) {
  561.         if (!jexpr) replace=decode(replace);
  562.         search=decode(search,literal);
  563.       }
  564.       if (literal) {
  565.         search=search.replace(/([.^$*+?()[{\\|])/g,"\\$1");
  566.         if (!jexpr) replace=replace.replace(/\$/g,"$$$$");
  567.       }
  568.       if (env('/B')) search="^"+search;
  569.       if (env('/E')) search=search+"$";
  570.       _g.loc=' in Search regular expression';
  571.       search=new RegExp(search,options);
  572.       _g.log='';
  573.       if (jexpr) {
  574.         _g.loc=' in Search regular expression';
  575.         test=new RegExp('.|'+search,options);
  576.         _g.loc='';
  577.         'x'.replace(test,function(){xcnt=arguments.length-2; return '';});
  578.         _g.replFunc='_g.replFunc=function($0';
  579.         for (var i=1; i<xcnt; i++) _g.replFunc+=',$'+i;
  580.         _g.replFunc+=',$off,$src){_g.loc=" in Replace code";'+( jmatch ? '_g.writeMatch(eval(_g.replace),$off,\''+lnPad+'\',\''+offPad+'\');_g.loc="";return $0;}' : 'var rtn=eval(_g.replace);_g.log="";return rtn;}' );
  581.         _g.defineReplFunc();
  582.       }
  583.       _g.replace=replace;
  584.     } else {                  // /T
  585.       if (translate.length>1) throw new Error(203, 'Invalid /T delimiter');
  586.       search=search.split(translate);
  587.       if (search.length>99) throw new Error(202, '/T expression count exceeds 99');
  588.       var replace=replace.split(translate);
  589.       if (search.length!=replace.length) throw new Error(201, 'Mismatched search and replace /T expressions');
  590.       _g.replace=[];
  591.       var j=1;
  592.       for (var i=0; i<search.length; i++) {
  593.         if (env('/X')) search[i]=decode(search[i],literal);
  594.         if (literal) {
  595.           search[i]=search[i].replace(/([.^$*+?()[{\\|])/g,"\\$1");
  596.         } else {
  597.           _g.loc=' in Search regular expression';
  598.           test=new RegExp('.|'+search[i],options);
  599.           _g.loc='';
  600.           'x'.replace(test,function(){xcnt=arguments.length-3;return '';});
  601.         }
  602.         if (j+xcnt>99) throw new Error(202, '/T expressions + captured expressions exceeds 99');
  603.         if (env('/B')) search[i]="^"+search[i];
  604.         if (env('/E')) search[i]=search[i]+"$";
  605.         if (jexpr) {
  606.           _g.replace[j]=replace[i];
  607.         } else {
  608.           replace[i]="'" + (env('/X')==''?replace[i]:decode(replace[i])).replace(/[\\']/g,"\\$&") + "'";
  609.           replace[i]=replace[i].replace(/\n/g, "\\n");
  610.           replace[i]=replace[i].replace(/\r/g, "\\r");
  611.           if (!literal) {
  612.             _g.replace[j]=replace[i].replace(
  613.               /\$([$&`0]|\\'|(\d)(\d)?)/g,
  614.               function($0,$1,$2,$3){
  615.                 return ($1=="$") ? "$":
  616.                        ($1=="&") ? "'+$0+'":
  617.                        ($1=="`") ? "'+$src.substr(0,$off)+'":
  618.                        ($1=="\\'") ? "'+$src.substr($off+$0.length)+'":
  619.                        (Number($1)-j<=xcnt && Number($1)>=j) ? "'+"+$0+"+'":
  620.                        (Number($2)-j<=xcnt && Number($2)>=j) ? "'+$"+$2+"+'"+$3:
  621.                        $0;
  622.               }
  623.             );
  624.           } else _g.replace[j]=replace[i];
  625.         }
  626.         j+=xcnt+1;
  627.       }
  628.       search='('+search.join(')|(')+')';
  629.       _g.loc=' in Search regular expression';
  630.       search=new RegExp( search, options );
  631.       _g.loc='';
  632.       _g.replFunc='_g.replFunc=function($0';
  633.       for (var i=1; i<j; i++) _g.replFunc+=',$'+i;
  634.       _g.replFunc+=',$off,$src){_g.loc=" in Replace code"; for (var i=1;i<arguments.length-2;i++) if (arguments[i]!==undefined) ';
  635.       _g.replFunc+= jmatch ? '{_g.writeMatch(eval(_g.replace[i]),$off,\''+lnPad+'\',\''+offPad+'\');_g.loc="";return $0;}}' : '{var rtn=eval(_g.replace[i]);_g.loc="";return rtn;}}';
  636.       _g.defineReplFunc();
  637.       jexpr=true;
  638.     }
  639.     var str1, str2;
  640.     var repl=jexpr?_g.replFunc:_g.replace;
  641.     if (srcVar) {
  642.       str1=env(srcVar);
  643.       str2=str1.replace(search,repl);
  644.       if (!jmatch) if (!alterations || str1!=str2) if (multi) {
  645.         output.Write(_g.fmtNum(ln,lnPad)+str2);
  646.       } else {
  647.         output.WriteLine(_g.fmtNum(ln,lnPad)+str2);
  648.       }
  649.       if (str1!=str2) _g.rtn=0;
  650.     } else if (multi){
  651.       var buf=1024;
  652.       str1="";
  653.       while (!input.AtEndOfStream) {
  654.         str1+=input.Read(buf);
  655.         buf*=2
  656.       }
  657.       str2=str1.replace(search,repl);
  658.       if (!jmatch) output.Write(_g.fmtNum(ln,lnPad)+str2);
  659.       if (str1!=str2) _g.rtn=0;
  660.     } else {
  661.       while (!input.AtEndOfStream && !quit) {
  662.         str2=str1=input.ReadLine();
  663.         ln++;
  664.         if (_g.begLn) str2=_g.callBeginLine(str2);
  665.         if (!skip) str2=str2.replace(search,repl);
  666.         if (_g.endLn) str2=_g.callEndLine(str2);
  667.         if (str2!==false && !jmatch && (!alterations || str1!=str2)) output.WriteLine(_g.fmtNum(ln,lnPad)+str2);
  668.         if (str1!=str2 && !jmatch) _g.rtn=0;
  669.       }
  670.     }
  671.   }
  672.   _g.main();
  673.   _g.loc=' in /JEND code';
  674.   eval(env( env('/V') ? env('/JEND') : '/JEND' ));
  675.   _g.loc='';
  676.   if (_g.inFile) input.close();
  677.   if (_g.outFile) output.close();
  678.   if (_g.outFile=='-') {
  679.     _g.fso.GetFile(_g.inFile).Delete();
  680.     _g.fso.GetFile(_g.inFile+'.new').Move(_g.inFile);
  681.   }
  682.   if (_g.tempFile) _g.fso.GetFile(_g.tempFile).Delete();
  683.   WScript.Quit(_g.rtn);
  684. } catch(e) {
  685.   WScript.Stderr.WriteLine("JScript runtime error"+_g.loc+": "+e.message);
  686.   WScript.Quit(3);
  687. }
  688. function decode(str, searchSwitch) {
  689.   str=str.replace(
  690.     /\\(\\|b|f|n|q|r|t|v|x80|x82|x83|x84|x85|x86|x87|x88|x89|x8[aA]|x8[bB]|x8[cC]|x8[eE]|x91|x92|x93|x94|x95|x96|x97|x98|x99|x9[aA]|x9[bB]|x9[cC]|x9[dD]|x9[eE]|x9[fF]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/g,
  691.     function($0,$1) {
  692.       switch ($1.toLowerCase()) {
  693.         case 'q':   return '"';
  694.         case 'x80': return '\u20AC';
  695.         case 'x82': return '\u201A';
  696.         case 'x83': return '\u0192';
  697.         case 'x84': return '\u201E';
  698.         case 'x85': return '\u2026';
  699.         case 'x86': return '\u2020';
  700.         case 'x87': return '\u2021';
  701.         case 'x88': return '\u02C6';
  702.         case 'x89': return '\u2030';
  703.         case 'x8a': return '\u0160';
  704.         case 'x8b': return '\u2039';
  705.         case 'x8c': return '\u0152';
  706.         case 'x8e': return '\u017D';
  707.         case 'x91': return '\u2018';
  708.         case 'x92': return '\u2019';
  709.         case 'x93': return '\u201C';
  710.         case 'x94': return '\u201D';
  711.         case 'x95': return '\u2022';
  712.         case 'x96': return '\u2013';
  713.         case 'x97': return '\u2014';
  714.         case 'x98': return '\u02DC';
  715.         case 'x99': return '\u2122';
  716.         case 'x9a': return '\u0161';
  717.         case 'x9b': return '\u203A';
  718.         case 'x9c': return '\u0153';
  719.         case 'x9d': return '\u009D';
  720.         case 'x9e': return '\u017E';
  721.         case 'x9f': return '\u0178';
  722.         default:    return searchSwitch===false ? $0 : eval('"'+$0+'"');
  723.       }
  724.     }
  725.   );
  726.   return str;
  727. }
  728. function lpad( val, pad ) {
  729.   var rtn=val.toString();
  730.   return (rtn.length<pad.length) ? (pad+rtn).slice(-pad.length) : val;
  731. }
复制代码
1

评分人数

    • CrLf: 感谢分享技术 + 1
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

不明觉厉!
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

TOP

本帖最后由 happy886rr 于 2016-3-27 20:49 编辑

回复 2# codegay
你的英语多少级了,为啥我看英文说明很吃力。话说julia都找不到汉化教程。

TOP

吓一跳,以为是纯P的....
原来是js混编,话说这代码风格和jren很像,可能同一作者

TOP

回复 3# happy886rr


    哈哈.初中水平,能刷刷英文网站论坛,但是经常有看不懂的东西,都假装看懂了,
我刷了好几年的美剧.电影,但是是说个人感觉对英语水平的进步帮助很有限.

julia 资料很缺,中文手册托管在,https://github.com/JuliaCN/julia_zh_cn

我一般是在这里阅读,http://julia-cn.readthedocs.org/zh_CN/latest/

julia的编辑器环境现在还需要自己配置,你用atom吧.下面这个博主写了图文教程.
Julia & Quant 博客 http://blog.csdn.net/wowotuo
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

TOP

回复 4# bailong360


    可以收录到bathcn哈.
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

TOP

本帖最后由 bailong360 于 2016-3-27 22:35 编辑

回复 6# codegay
已收录
====
将会收录=_=,列表文件好像和CrLf兄的没同步上...

TOP

回复 7# bailong360


    我还以为你说的jren是人名呢,
确实是同一个人写的.
http://www.dostips.com/forum/viewtopic.php?t=6081
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

TOP

回复 8# codegay


    jren 是巨人的意思

TOP

好东西,终于明白了

TOP

返回列表