Batch - Extract string before the specified character

How to get the string before the character hyphen? The following code gets the string after the hyphen. How can I reverse this?

set string=1.0.10-SNAPSHOT

echo %string:*-=%

SNAPSHOT

But I want the 1.0.10 instead of SNAPSHOT


Use for with delims like this:

set string=1.0.10-SNAPSHOT
for /f "delims=-" %%i in ("%string%") do echo %%i

The following code gets the string after the hyphen. How can I reverse this?

echo %string:*-=%
  • See: Split string into substrings based on delimiter

...And there’s a kludgy way to get the start of a string up to the first occurrence of the substring: - Sponge Belly

set "head=%str:x=" & rem."%"
  • Porting to your variable and delimiter:
set "string=%string:Your_Delimiter=" & rem."%"
set "string=%string:-=" & rem."%"
  • A shorter version would be:
echo\%string:-=&rem\%
  • This also works by replacing rem\ with ::
echo\%string:-=&::%
  • Outputs:
1.0.10

Obs.: Use without "double quotes" when echoing the variable so as not to escape the self-expanding variable

> set string=1.0.10-SNAPSHOT
> echo %string:-=&::% "%string:-=&::%"
       1.0.10         "1.0.10&::SNAPSHOT"


If the non-numeric string is always this one or it's always the same length, you can also remove the last 9 characters:

set string=1.0.10-SNAPSHOT

echo %string:~0,-9%

1.0.10

A non-loop alternative would be to use the current output of your substring as replace:

 cmd /v /c echo\ !string:-%string:*-=%=!
  • Outputs:
1.0.10

Additional Resources:

  • Set /?
  • DelayedExpansion (Refer: cmd /v /c)
  • Set variable=variable:substrings | DOS - String Manipulation