24

What is the best way to remove all text in a string after a specific character? In my case "=" and after another character in my case a ,, but keep the text between?

Sample input

=keep this,

4

5 回答 5

45

另一种方法是使用 operator -replace

$TestString = "test=keep this, but not this."

$NewString = $TestString -replace ".*=" -replace ",.*"

.*=表示最多包含等号的任意数量的字符。

,.*表示逗号后跟任意数量的字符。

由于您基本上删除了字符串的这两个部分,因此您不必指定一个空字符串来替换它们。您可以使用多个 -replace,但请记住顺序是从左到右的。

于 2013-10-03T21:27:18.833 回答
4
$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]

返回

keep this
于 2013-10-03T20:29:40.867 回答
2

这应该做你想要的:

C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this
于 2013-10-03T20:23:53.103 回答
2

这真的很老了,但我想为其他可能偶然发现它的人添加我的细微变化。正则表达式是强大的东西。

保留等号和逗号之间的文本:

-replace "^.*?=(.*?),.*?$",'$1'

此正则表达式从行首开始,擦除所有字符直到第一个等号,捕获每个字符直到下一个逗号,然后擦除每个字符直到行尾。然后它将整行替换为捕获组(括号内的任何内容)。它将匹配包含至少一个等号后跟至少一个逗号的任何行。它类似于 Trix 的建议,但与该建议不同的是,这不会匹配仅包含等号或逗号的行,它必须按顺序包含两者。

于 2019-05-13T20:19:33.320 回答
0

我在上面引用了@benjamin-hubbard 的答案来解析dnscmdfor A 记录的输出,并生成 IP 和主机名的 PHP“字典”/键值对。我将多个 args 串-replace在一起以用空替换文本或tab格式化 PHP 文件的数据。

$DnsDataClean = $DnsData `
    -match "^[a-zA-Z0-9].+\sA\s.+" `
    -replace "172\.30\.","`$P." `
    -replace "\[.*\] " `
    -replace "\s[0-9]+\sA\s","`t"

$DnsDataTable = ( $DnsDataClean | `
    ForEach-Object { 
        $HostName = ($_ -split "\t")[0] ; 
        $IpAddress = ($_ -split "\t")[1] ; 
        "`t`"$IpAddress`"`t=>`t'$HostName', `n" ;
    } | sort ) + "`t`"`$P.255.255`"`t=>`t'None'"

"<?php
`$P = '10.213';
`$IpHostArr = [`n`n$DnsDataTable`n];

?>" | Out-File -Encoding ASCII -FilePath IpHostLookups.php

Get-Content IpHostLookups.php
于 2018-07-20T00:11:48.703 回答