Powershell:从字符串中提取文本

时间:2012-02-02 13:33:34

标签: regex string text powershell

如何从字符串中提取“程序名称”。字符串将如下所示:

  

%O0033(SUB RAD MSD 50R III)G91G1X-6.4Z-2.F500 G3I6.4Z-8。 G3I6.4   G3R3.2X6.4F500 G91G0Z5。 G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2。   M99%

程序名称为(SUB RAD MSD 50R III)。将结果存储在另一个字符串中很好。我正在学习powershell,所以任何解释你的答案将不胜感激。

4 个答案:

答案 0 :(得分:45)

以下正则表达式在括号之间提取任何内容:

PS> $prog = [regex]::match($s,'\(([^\)]+)\)').Groups[1].Value
PS> $prog
SUB RAD MSD 50R III


Explanation (created with RegexBuddy)

Match the character '(' literally «\(»
Match the regular expression below and capture its match into backreference number 1 «([^\)]+)»
   Match any character that is NOT a ) character «[^\)]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character ')' literally «\)»

检查以下链接:

http://www.regular-expressions.info

http://powershell.com/cs/blogs/tobias/archive/2011/10/27/regular-expressions-are-your-friend-part-1.aspx

http://powershell.com/cs/blogs/tobias/archive/2011/12/02/regular-expressions-are-your-friend-part-2.aspx

http://powershell.com/cs/blogs/tobias/archive/2011/12/02/regular-expressions-are-your-friend-part-3.aspx

答案 1 :(得分:15)

如果程序名始终是()中的第一项,并且不包含其他的),那么$yourstring -match "[(][^)]+[)]"匹配的结果将是$Matches[0]

答案 2 :(得分:5)

只需添加非正则表达式解决方案:

'(' + $myString.Split('()')[1] + ')'

这会将字符串拆分为括号,并从数组中获取包含程序名称的字符串。

如果您不需要括号,请使用:

$myString.Split('()')[1]

答案 3 :(得分:1)

使用-replace

 $string = '% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8.G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %'
 $program = $string -replace '^%\sO\d{4}\((.+?)\).+$','$1'
 $program

SUB RAD MSD 50R III