正则表达式 - 如何将此字符串分成两部分

Regex - How to split this string in two parts

我想把这个字符串分成两部分:

C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US

我希望它总是在 Setup.exe 之后拆分,所以它应该是 :

$part1 = "C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe"
$part2 = "/P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US"

执行此操作的函数应该是什么?

谢谢

$string = "C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US" 
$array = $string -Split "(Setup.exe)"
$array[0]+$array[1]
$array[2]

可以有其他简单的方法。这是一种方法。

这里有一些供您选择的选择:

$string = 'C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US'

方法一:使用-split

$part1, $part2 = $string -split '^(.+\.exe)\s(.+)$'
$part1   # --> C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe
$part2   # --> /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US

方法二:使用[regex].Match()

$part1, $part2 = ([regex]'(?i)^(.+\.exe)\s(.+)$').Match($string).Groups[1..2].Value
$part1   # --> C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe
$part2   # --> /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US

方法三:使用-replace结合方法.Split()

$part1, $part2 = ($string -replace '^(.+\.exe)\s(.+)$', '|').Split('|')
$part1   # --> C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe
$part2   # --> /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US

方法四:使用字符串方法.IndexOf().Substring()

$split = $string.IndexOf('.exe')
if ($split -ge 0) {
    $part1 = $string.Substring(0, $split + 4)
    $part2 = $string.Substring($split + 5)
}

$part1   # --> C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe
$part2   # --> /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US

只是拆分空白并将它们放回原处。根据您用作 -argumentlist 或与调用运算符的用途,您甚至可能不必将 $part2 数组连接在一起。

$string = 'C:\Program Files\Autodesk\DWG TrueView 2021 - English\Setup\en-us\Setup\Setup.exe /P {28B89EEF-4356-0409-0100-CF3F3A09B77D} /M AOEM /language en-US'
$split = -split $string

$split
C:\Program
Files\Autodesk\DWG
TrueView
2021
-
English\Setup\en-us\Setup\Setup.exe
/P
{28B89EEF-4356-0409-0100-CF3F3A09B77D}
/M
AOEM
/language
en-US

$part1 = $split[0..5] -join ' '
$part2 = $split[6..$split.length] -join ' '
# $part2 = $split[6..$split.length]