批处理文件:查找子字符串是否在字符串中(不在文件中) [英] Batch file: Find if substring is in string (not in a file)

查看:35
本文介绍了批处理文件:查找子字符串是否在字符串中(不在文件中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在批处理文件中,我有一个字符串 abcdefg.我想检查 bcd 是否在字符串中.

In a batch file, I have a string abcdefg. I want to check if bcd is in the string.

不幸的是,似乎我找到的所有解决方案都是在文件中搜索子字符串,而不是搜索子字符串的字符串.

Unfortunately it seems all of the solutions I'm finding search a file for a substring, not a string for a substring.

有没有简单的解决方案?

Is there an easy solution for this?

推荐答案

是的,您可以使用替换并检查原始字符串:

Yes, you can use substitutions and check against the original string:

if not x%str1:bcd=%==x%str1% echo It contains bcd

%str1:bcd=% 位会将 str1 中的 bcd 替换为空字符串,使其与原始字符串不同.

The %str1:bcd=% bit will replace a bcd in str1 with an empty string, making it different from the original.

如果原始版本中不包含bcd字符串,则修改后的版本将相同.

If the original didn't contain a bcd string in it, the modified version will be identical.

使用以下脚本进行测试将显示它的实际效果:

Testing with the following script will show it in action:

@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal

以及各种运行的结果:

c:	estarea> testprog hello

c:	estarea> testprog abcdef
It contains bcd

c:	estarea> testprog bcd
It contains bcd

一些注意事项:

  • if 语句是这个解决方案的核心,其他一切都是支持的东西.
  • 等式两边前面的x是为了保证字符串bcd正常工作.它还可以防止某些不正确"的起始字符.
  • The if statement is the meat of this solution, everything else is support stuff.
  • The x before the two sides of the equality is to ensure that the string bcd works okay. It also protects against certain "improper" starting characters.

这篇关于批处理文件:查找子字符串是否在字符串中(不在文件中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆