Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 我可以从一个字符串中删除一个子字符串,该字符串从一个已知的位置开始,到一个给定的字符结束吗?_String_Powershell_Replace_Substring - Fatal编程技术网

String 我可以从一个字符串中删除一个子字符串,该字符串从一个已知的位置开始,到一个给定的字符结束吗?

String 我可以从一个字符串中删除一个子字符串,该字符串从一个已知的位置开始,到一个给定的字符结束吗?,string,powershell,replace,substring,String,Powershell,Replace,Substring,我需要提取字符串的部分,但我并不总是知道长度/内容 例如,我尝试过将字符串转换为XML或JSON,但找不到任何其他方法来实现我想要的 示例字符串: 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah' '字符串名称的其他部分=“SomeRandomAmountOfCharacters”等等' 我需要删除的内容总是以属性名开始,以结束双引号结束。所以我可以说我想删除从Name=”开始的子字符串,直到我们到

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

例如,我尝试过将字符串转换为XML或JSON,但找不到任何其他方法来实现我想要的

示例字符串:

'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah' '字符串名称的其他部分=“SomeRandomAmountOfCharacters”等等' 我需要删除的内容总是以属性名开始,以结束双引号结束。所以我可以说我想删除从Name=”开始的子字符串,直到我们到达结束“

预期结果:

'Other parts of the string blah blah' “字符串的其他部分诸如此类”
这里有一个很好的参考:

就你而言

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


这将用一个空格替换匹配的字符串,包括周围的空格。

看看类似的内容,了解它是如何工作的

$pattern = '(.*)Name=".*" (.*)'
$str = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'

$ret = $str -match $pattern

$out = $Matches[1]+$Matches[2]

$str
"===>"
$out

另请参见:

您将希望执行类似的操作

$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)
如果您有一个多行字符串,请添加到您的表达式中。

这正是我需要的。其他答案很好,但您考虑了附加属性的可能性。我以前从未见过模式
*?
。星号后的问号起什么作用?不要紧,我找到了解释:这是一个很好的答案斯韦尔,谢谢你。让我接近我所需要的。
$s = 'Other parts of the string Name="SomeRandomAmountOfCharacters" blah blah'
$s -replace ' Name="[^"]*"'