I have a string base
of the form *+*
. I want to get everything before the +.
For example, if base=foo+bar
, I want to get foo
.
I've tried doing it with string replacement
set left=%base:+*=%
But this results in left
storing foo+bar
.
Interestingly, string replacement works for getting everything right of the +:
set right=%base:*+=%
Is +*
being replaced by +
(i.e. the wildcard is substituting for 0 characters)? Is there a better way to accomplish my task?
EDIT: I'm actually doing this in a for loop. Therefore, delayed expansion is on and (I think) I need to use !. Full code here:
for /d %%d in (*+*) do (
set base=%%d
set right=!base:*+=!
set left=!base:+*=! ::this part doesn't work
if !left:~-2!==!right:~-2! ( ::do only if last 2 chars match
copy %%d mirrors
copy %%d\%%d_montage.bmp mirrors
)
)
EDIT 2: Comments in code above are only for readability here on SO. ::-style comments may not work correctly in for loops.
You may use this trick:
@echo off
set "base=foo+bar"
set "left=%base:+=" & set "right=%"
echo Left=%left%
echo Right=%right%
EDIT: If you want to use the method inside a for
loop, use it this way:
@echo off
setlocal EnableDelayedExpansion
for %%a in ("one+two" "first+last") do (
call :separate %%a
echo Left=!left!
echo Right=!right!
echo/
)
goto :EOF
:separate
set "base=%~1"
set "left=%base:+=" & set "right=%"
exit /B
I've never had much luck with environment variable string replacement with wildcards, probably because of the right issue wOxxOm notes.
I'd tend to favor this method here:
for /f "tokens=1,2 delims=+" %a in ('echo %base%') do (
set left=%a
set right=%b
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With