Reputation: 393
I want to extract a sub-string based on pattern from a given string in batch script.
Example:
Input : ABCDEF-x32-32.12.20-298-date-20-12-17.exe
Required Output : 32.12.20-298 (i.e. <number>.<number>.<number>-<number>)
Regex (may be) : [0-9]+\.[0-9]+\.[0-9]+-[0-9]+
How do I implement this in batch script??? I tried to implement the same using 'For' and 'findstr', but failed to do so.
Upvotes: 0
Views: 3215
Reputation: 130819
Windows batch does not have a good regular expression tool. The FINDSTR command has very limited (non-standard, and bugged) regex support. And it only can return entire lines that contain a match.
There are native Windows scripting languages that do have good support. PowerShell certainly does, And so do JScript and VBScript (available via CSCRIPT).
If you really want a pure script based regex solution from within a batch file, then you can use JREPL.BAT. It is hybrid batch/JScript that conveniently brings the power of JScript regular expressions to the batch world.
Full documentation is available via jrepl /?
, or jrepl /??
for paged help. Another important help command is jrepl /?options
to get a summary of all available options, and jrepl /?help
to get a summary of all available help.
Normally JREPL is used to perform a find/replace operation. But the /MATCH
option ignores the required replace string and simply outputs the matching text.
Normally JREPL reads from stdin or a file. But the /S
option reads the input from a variable.
The output is typically stdout or a file. But the /RTN
option saves the result to an environment variable (entire result must fit within ~8kb).
@echo off
setlocal
set "str=ABCDEF-x32-32.12.20-298-date-20-12-17.exe"
:: Extract the string and print to the screen
call jrepl "[0-9]+\.[0-9]+\.[0-9]+-[0-9]+" "" /match /s str
:: Extract the string and store it in variable out.
call jrepl "[0-9]+\.[0-9]+\.[0-9]+-[0-9]+" "" /match /s str /rtn out
Upvotes: 2