【问题标题】:Delete portion of string from variable including and after pattern with batch file从变量中删除字符串的一部分,包括带有批处理文件的模式和之后的模式
【发布时间】:2019-01-14 16:44:52
【问题描述】:

这可能吗?

例如,假设我有一个包含以下字符串的变量:

str=This is a test - because it can be

我需要做的是能够从 %str% 变量中搜索和删除所有内容,包括“空格、破折号、空格”之后的所有内容。所以,我最终会得到:

str=This is a test

我可以轻松地对单个字符执行此操作,删除或替换该单个字符,但不知道如何使用模式来执行此操作。

提前感谢。

【问题讨论】:

    标签: batch-file search replace


    【解决方案1】:

    可以使用 syntax-replacement 解决您的问题。我建议您在这里阅读更多信息:https://ss64.com/nt/syntax-replace.html

    为了您的问题,格式设置为SET _result=%_test:ab=%。这将允许您从所需的字符串中删除已定义的文本。

    代码:

    @echo off
    
    ::Define text as string
    set str=This is a test - because it can be
    
    ::Remove string
    set str=%str: - because it can be=%
    
    ::Echo result
    echo %str%
    
    pause
    

    结果:

    This is a test
    

    【讨论】:

    • 是的,但是如果“-因为它可以”字符串是完全随机的呢?
    • @user3208239 过程是一样的。您可以使用语法替换来提取字符串的第一部分并删除其后的所有内容。另一种方法是完全删除This is a test 之后的所有内容。请看一下提供的一面。
    • @JohnKens,我认为 OP 说得很清楚,他们不会知道 ` - ` 之前或之后的内容。
    • @JohnKens:这样更简单:::Define text as string & set str=This is a test - because it can be & ::Get result & set str=This is a test ;)
    • @Aacini haha​​ def is.
    【解决方案2】:

    这使用字符串替换来按空格分割字符串。它将变量的第一部分重新分配回 str 变量,第二部分通过使用 nul 重定向而被忽略。

    @echo off
    set "str=This is a test - because it can be"
    (set "str=%str: - =" & set /p "=%")<nul >nul
    echo %str%
    pause
    

    【讨论】:

      【解决方案3】:

      有很多方法可以达到相同的结果:

      :: Q:\Test\2018\08\07\SO_51729389.cmd
      @Echo off & setlocal
      :: you should always enclose the var=content in double quotes
      Set "str=This is a test - because it can be"
      Echo Original [%str%]
      
      :: method 1 shuffle: string substitution with the asterisk
      Set "str2=%str:* - =%"
      Call Echo method 1 [%%str: - %str2%=%%]
      
      :: method 2 change the " - " to a single char delims and use for /F
      for /f "delims=|" %%A in ("%str: - =|%") do Echo method 2 [%%A]
      
      :: method 3 similar to Squashman's
      Set "str3=%str: - ="&Set "_=%"
      Echo method 3 [%str3%]
      

      示例输出:

      > Q:\Test\2018\08\07\SO_51729389.cmd
      Original [This is a test - because it can be]
      method 1 [This is a test]
      method 2 [This is a test]
      method 3 [This is a test]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        • 2019-06-28
        • 2013-08-04
        • 2021-06-20
        • 2016-05-30
        • 2011-02-15
        相关资源
        最近更新 更多