【问题标题】:Extract text from a string从字符串中提取文本
【发布时间】:2012-02-25 03:51:26
【问题描述】:

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

% 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,因此对您的答案的任何解释将不胜感激。

【问题讨论】:

  • 程序名总是在 () 中,还是总是从第 7 个字符开始?
  • 我正在使用的其他文件中有多行带有“()”。我需要的程序在第一个括号中。第一行的模式是“%”,第二行以“O”开头,然后是一个 4 位数字“????”然后程序是在括号后海峡。希望这对大家有所帮助

标签: regex string text powershell


【解决方案1】:

如果程序名始终是 () 中的第一项,并且不包含除末尾之外的其他 ),则 $yourstring -match "[(][^)]+[)]" 进行匹配,结果将在 $Matches[0]

【讨论】:

  • ...由于 -match 返回一个布尔值,您可能希望在表达式上下文中使用类似 if($something -match "regexp") { $Matches[0] } else { '' } 的东西。
【解决方案2】:

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

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

【讨论】:

  • 感谢您的回答。你能解释一下,或者我怎么能了解正则表达式?任何推荐的好网站。
【解决方案3】:

使用 -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

【讨论】:

  • 多行带有“()”。模式是
  • 正则表达式针对新要求进行了调整
【解决方案4】:

只是添加一个非正则表达式解决方案:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多