Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression matching in PowerShell

Tags:

Is there an elegant one-liner for doing the following?

$myMatch = "^abc(.*)" $foo -match $myMatch $myVar = $matches[1] 

I'm interested in the $myVar variable...

like image 658
ted Avatar asked May 04 '11 09:05

ted


People also ask

Which PowerShell operator will match a regular expression?

The Match Operator One of the most useful and popular PowerShell regex operators is the match and notmatch operators. These operators allow you to test whether or not a string contains a specific regex pattern. If the string does match the pattern, the match operator will return a True value.

Can regex be used in PowerShell?

Regular expressions (regex) match and parse text. The regex language is a powerful shorthand for describing patterns. Powershell makes use of regular expressions in several ways. Sometimes it is easy to forget that these commands are using regex becuase it is so tightly integrated.

What is the purpose of a regular expression in PowerShell?

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. Matches the beginning of the line.


1 Answers

Just use -replace:

$foo = 'abcDEF' $myMatch = "^abc(.*)" $myVar = $foo -replace $myMatch,'$1' #$myVar contains DEF 
like image 61
stej Avatar answered Oct 21 '22 12:10

stej