【问题标题】:Extract a number from a string in Windows shell script从 Windows shell 脚本中的字符串中提取数字
【发布时间】:2013-07-23 17:38:13
【问题描述】:

我有一个像这样的字符串脚本文件 hello-1234-something。我需要使用批处理文件获取 1234。但是数字 1234 不一样,它一直在变化我需要在字符串中找到数字并取出数字。我是批处理文件编程的新手。我想批量这样做

【问题讨论】:

    标签: windows for-loop batch-file cmd


    【解决方案1】:

    试试这个:

    @ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
    SET "teststring=abcDEFG1234ABSdefh"
    
    FOR %%a IN (
        a b c d e f g h i j k l m n o p q r s t u v w x y z
            ) DO (
        SET "teststring=!teststring:%%a=!"
    )
    ECHO %teststring%
    

    注意:这不适用于特殊字符,例如:<>&|!^

    【讨论】:

      【解决方案2】:

      如果您的字符串始终具有字符串连字符数字连字符字符串的形式(例如foo-23-barsome-205-orother、...),您可以执行以下操作:

      @echo off
      
      setlocal
      
      set "string=foo-23-bar"
      
      for /f "tokens=2 delims=-" %%n in ("%string%") do set "num=%%n"
      
      echo %num%
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-08
        • 1970-01-01
        • 1970-01-01
        • 2019-12-10
        • 1970-01-01
        • 2021-09-25
        • 1970-01-01
        相关资源
        最近更新 更多