Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

regex - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

1.4m articles

1.4m replys

5 comments

56.9k users

...