【问题标题】:Can I remove a substring from a string starting at a known position and ending at a given character?我可以从已知位置开始并以给定字符结束的字符串中删除子字符串吗?
【发布时间】:2019-06-02 14:52:17
【问题描述】:

我需要提取字符串的各个部分,但我并不总是知道长度/内容。

例如,我尝试将字符串转换为 XML 或 JSON,但无法想出任何其他方法来实现我正在寻找的内容。

示例字符串:

'字符串的其他部分 Name="SomeRandomAmountOfCharacters" blah blah'

我需要删除的内容始终以属性名称开头,并以右双引号结尾。所以我可以说我想删除从 Name=" 开始的子字符串,直到我们到达结束 "?

预期结果:

'字符串的其他部分等等等等'

【问题讨论】:

    标签: string powershell replace substring


    【解决方案1】:

    你会想做这样的事情

    $s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
    $s -replace ' Name=".*?"'
    

    或者像这样:

    $s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
    $s -replace ' Name="[^"]*"'
    

    避免无意中删除字符串的其他部分,以防它包含多个属性或额外的双引号。 .*? 是对除换行符以外的任何字符序列的非贪婪匹配,因此它将匹配下一个双引号。 [^"]* 是一个字符类,匹配最长连续的非双引号字符序列,因此它也会匹配下一个双引号。

    如果您有一个多行字符串,您还需要将其他构造 (?ms) 添加到您的表达式中。

    【讨论】:

    • 这正是我所需要的。其他答案很好,但您考虑了其他属性的可能性。
    • 我以前从未见过.*? 的模式。星号后面的问号起什么作用?
    • 没关系,我找到了解释:stackoverflow.com/questions/3075130/…
    【解决方案2】:

    这是一个很好的参考:https://www.regular-expressions.info/powershell.html

    你的情况

    $s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
    $s -replace '\W*Name=".*"\W*', " "
    

    $newString = $s -replace 'W*Name=".*"\W*', " "
    

    这会将您的匹配字符串(包括周围的空格)替换为一个空格。

    【讨论】:

    • 这是一个很好的答案,谢谢。让我非常接近我需要的东西。
    【解决方案3】:

    看看这样的东西并了解它是如何工作的。

    $pattern = '(.*)Name=".*" (.*)'
    $str = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
    
    $ret = $str -match $pattern
    
    $out = $Matches[1]+$Matches[2]
    
    $str
    "===>"
    $out
    

    另请参阅:https://regex101.com/r/wM2xlc/1

    【讨论】:

      猜你喜欢
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 2023-03-27
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多