Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract text from a string

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.

like image 844
resolver101 Avatar asked Feb 02 '12 13:02

resolver101


People also ask

How do I extract part of a text string?

1. Select a cell that used to place the extracted substring, click Kutools > Formula Helper > Text > Extract strings between specified text. 2. In the Formulas Helper dialog, go to the Arguments input section, then select or directly type the cell reference and the two characters you want to extract between.

How do I extract just text?

VBA: Extract text only Save the code and close the window, then type this formula =TextOnly(A1) (A1 is the first row cell in your list range you want to extract text only from) into a blank cell, press Enter button, then fill the handle to the range you want.

How do I extract letters from a cell in Excel?

For example, the formula =LEN() gives back the number of characters in a cell. So =LEFT(A1,LEN(A1)-2) extracts the entire text in a cell except the last two characters.


1 Answers

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:

  • Regular-Expressions.info
  • Regular Expressions Are Your Friend (Part 1)
  • Regular Expressions Are Your Friend (Part 2)
  • Regular Expressions Are Your Friend (Part 3)
like image 183
Shay Levy Avatar answered Sep 24 '22 00:09

Shay Levy