获取字符串

时间:2017-07-04 16:41:35

标签: batch-file cmd substring

我找到了一些关于完成以下内容的指导:

我有一个变量,其内容如下:

varname = asdfiuytgy12$gggsy22.oihbcxew

varname = oiujedc$thisisit.oiju

$.正是我的伙伴,我需要了解其中的内容gggsy22thisisit

我需要使用批处理来创建一个简单的bat文件。我希望有人可以提供一些指导。

修改 - (来自评论部分)

实际上我的一个朋友帮忙了,但它确实有效,但有很多界限:

Set "sstr=$"
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos1=%pos%"
Set "sstr=."
SET stemp=%nameVar%&SET pos=0

:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
    SET stemp=%stemp:~1%
    IF DEFINED stemp GOTO loop
    SET pos=0
)
Set "pos2=%pos%"
set /a "pos2=%pos2%-%pos1%-1"
call set env=%%nameVar:~%pos1%,%pos2%%%

2 个答案:

答案 0 :(得分:3)

@echo off
set "varname=asdfiuytgy12$gggsy22.oihbcxew"
for /f "tokens=2 delims=$." %%a in ("%varname%") do set "sub=%%a"

答案 1 :(得分:1)

以下几乎适用于任何情况。唯一可能破坏代码的是,如果字符串包含引号",后跟一个毒物字符,如&|等。

@echo off
setlocal
set "str=oiujedc$thisisit.oiju"

:: Verify string exists and has the proper format
echo "%str%"|findstr "\$.*\." >nul || (echo Value not found & exit /b)

:: Extract the value
:: The extra "x" is needed in case there is no character between $ and .,
:: in which case the result should be No Value (result variable not defined)
for /f "delims=." %%A in ("x%str:*$=%") do set "val=%%A"
set "val=%val:~1%"

:: Show the result
echo value = "%val%"

可以通过合并延迟扩展来制作防弹变体。