Extract text from a string

前端 未结 4 951
孤街浪徒
孤街浪徒 2020-12-05 04:30

How do I extract the \"program name\" from a string. The string will look like this :

% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8. G

相关标签:
4条回答
  • 2020-12-05 05:00

    Just to add a non-regex solution:

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

    This splits the string at the parentheses and takes the string from the array with the program name in it.

    If you don't need the parentheses, just use:

    $myString.Split('()')[1]
    
    0 讨论(0)
  • 2020-12-05 05:09

    If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]" does the matching, result will be in $Matches[0]

    0 讨论(0)
  • 2020-12-05 05:12

    Using -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
    
    0 讨论(0)
  • 2020-12-05 05:16

    The following regex extract anything between the parenthesis:

    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 «\)»
    

    Check these links:

    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

    0 讨论(0)
提交回复
热议问题