使用批处理文件,在另一个字符串中的子字符串匹配后获取 4 个字符?

发布于 2024-12-15 13:18:37 字数 462 浏览 0 评论 0原文

我试图想出一种提取字符串中子字符串匹配后出现的 4 个字符的方法。我能想到的最接近的东西看起来效率非常低,甚至效果也不是很好。有谁知道更好的方法吗?

@echo off
cls
SET "_TMPVAR=Ports|http:8000|https:8443|"
SET _TMPVAR=%_TMPVAR:|=,%
FOR /F "tokens=1-3 delims=," %%m in ("%_TMPVAR%") do (
  SET "_TMPVAR1=%%n"
  SET "_TMPVAR2=%%o"
)
SET _HTTPS=0000
IF "%_TMPVAR1:~4,1%"=="s" (
  SET "_HTTPS=%_TMPVAR1:~-4%"
)
IF "%_TMPVAR2:~4,1%"=="s" (
  SET "_HTTPS=%_TMPVAR2:~-4%"
)
SET _
ECHO SSL Port is %_HTTPS%
pause

I am trying to come up with a method of extracting 4 characters that occur after a substring match in a string. The closest thing I could come up with is terribly inefficient looking and doesn't even work all that well. Does anyone know a better way of doing this?

@echo off
cls
SET "_TMPVAR=Ports|http:8000|https:8443|"
SET _TMPVAR=%_TMPVAR:|=,%
FOR /F "tokens=1-3 delims=," %%m in ("%_TMPVAR%") do (
  SET "_TMPVAR1=%%n"
  SET "_TMPVAR2=%%o"
)
SET _HTTPS=0000
IF "%_TMPVAR1:~4,1%"=="s" (
  SET "_HTTPS=%_TMPVAR1:~-4%"
)
IF "%_TMPVAR2:~4,1%"=="s" (
  SET "_HTTPS=%_TMPVAR2:~-4%"
)
SET _
ECHO SSL Port is %_HTTPS%
pause

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千秋岁 2024-12-22 13:18:38

改进它的一种方法是消除看似不必要的逗号替换:

SET "_TMPVAR=Ports|http:8000|https:8443|"
FOR /F "tokens=1-3 delims=|" %%m in ("%_TMPVAR%") do (
  SET "_TMPVAR1=%%n"
  SET "_TMPVAR2=%%o"
)

此外,您可以利用分隔符列表来拆分 | : 分解您的方案和端口,允许您将逻辑放入 FOR 语句中:

@echo off
cls
SET "_TMPVAR=Ports|http:8000|https:8443|"
SET _HTTPS=0000
FOR /F "tokens=2-7 delims=|:" %%a in ("%_TMPVAR%") do (
    IF %%a==https SET _HTTPS=%%b
    IF %%c==https SET _HTTPS=%%d
    IF %%e==https SET _HTTPS=%%f
)
SET _
ECHO SSL Port is %_HTTPS%

使用分隔符行为的优点是它允许使用任意长度的端口号。

One way to improve it is to eliminate the seemingly unnecessary comma replacement:

SET "_TMPVAR=Ports|http:8000|https:8443|"
FOR /F "tokens=1-3 delims=|" %%m in ("%_TMPVAR%") do (
  SET "_TMPVAR1=%%n"
  SET "_TMPVAR2=%%o"
)

Further, you can take advantage of the delimiter list to split on | and : to break up your schemes and ports, allowing you to put the logic inside the FOR statement:

@echo off
cls
SET "_TMPVAR=Ports|http:8000|https:8443|"
SET _HTTPS=0000
FOR /F "tokens=2-7 delims=|:" %%a in ("%_TMPVAR%") do (
    IF %%a==https SET _HTTPS=%%b
    IF %%c==https SET _HTTPS=%%d
    IF %%e==https SET _HTTPS=%%f
)
SET _
ECHO SSL Port is %_HTTPS%

An advantage of using the delimiter behavior is that it allows for port numbers of any length.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文