39

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. G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %

The program name is (SUB RAD MSD 50R III). Storing the result in another string is fine. I'm learning powershell so any explaination of your answers will be appreciated.

pppery
  • 3,731
  • 22
  • 33
  • 46
resolver101
  • 2,155
  • 11
  • 41
  • 53
  • Will program name always be in the (), or will it always start at 7th character? – Andrey Marchuk Feb 02 '12 at 13:37
  • There are multiple lines with "()" in the other files im working with. The program i need is in the first brackets. The pattern is "%" on the first line, second line starts with "O" and then a 4 digit number "????" and then the program is in the brackets strait after. Hope this helps guys – resolver101 Feb 03 '12 at 11:19

4 Answers4

68

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

Further Reading:

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
20

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]

jsvnm
  • 676
  • 6
  • 10
  • 1
    ...and since `-match` returns a boolean, you probably want something like `if($something -match "regexp") { $Matches[0] } else { '' }` in an expression context. – Nickolay May 10 '20 at 15:01
7

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]
Rynant
  • 23,153
  • 5
  • 57
  • 71
1

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
mjolinor
  • 66,130
  • 7
  • 114
  • 135