检测变量是否包含字符串,然后批量查找该字符串之后的单词

时间:2019-12-28 16:03:21

标签: batch-file variables cmd

我想制作一个批处理文件,以检测变量中某处是否存在单词I'm,然后找到I'm之后的单词并将其放在变量中。就像DadBot。这是我的代码:

if /I "%message:~0,4%"=="i'm "

但是我希望这发生在字符串的任何地方。有什么办法吗?

3 个答案:

答案 0 :(得分:0)

您可以这样做:

@echo off
set token=1
echo "%message%" | find "I'm" >nul 2>&1 && goto yeah
goto notmatch 

:yeah
for /f "tokens=%token% delims= " %%a in ('echo "%message%"') do if "%%~a"=="I'm" set /a myword=token+1 & goto break
set /a token += 1
goto yeah

:break
for /f "tokens=%myword% delims= " %%a in ('echo "%message%"') do set theword=%%a
echo %theword%
pause >nul 

:notmach
echo not found
pause

答案 1 :(得分:0)

第一步是检查搜索字符串(I'm)。如果找到了它,则剪切所有内容直到搜索字符串,然后从其余的单词中得到第一个单词:

@echo off
setlocal
call :GetName "I'm Stephan"
echo %name%
call :GetName "You know, I'm Stephan!"
echo %name%
call :GetName "I'm Stephan, as you know"
echo %name%
call :GetName "There is no search string"
echo %name%
goto :eof

:GetName
set "var=%~1"
if "%var:I'm =x%" == "%var%" set "name=none" & goto :eof
set "var=%var:*I'm =%"
for /f "delims=.,;! " %%a in ("%var%") do set "name=%%a"

答案 2 :(得分:0)

我看到您已经选择了答案。这是使用PowerShell的另一种方法。如果您使用的是受支持的Windows系统,则可以使用PowerShell。

使用正则表达式功能强大且可维护。

$strings = @(
    "I'm Stephan"
    "You know, I'm Stephan!"
    "I'm Stephan, as you know"
    "There is no search string"
)

foreach ($string in $strings) {
    if ($string -match "i'm ([a-zA-Z]*)") {
        $Matches[1]
    } else {
        "No match for === $string"
    }
}