Register Log in

Ministry of Innovation / Business of Technology

A guided tour of the Microsoft Command Shell


Syntax: regular expressions

Regular expressions

MSH provides some unique syntactic sugar that allows you to perform switch comparisons on strings with regular expressions:

msh> switch -regex ($var) {
  ".*[0-9]+" { "the string ends with a number!" }
  default { "the string doesn't end with a number." }

In Bash, the awk utility is often used to compare a string against regular expressions. Unfortunately, the awk syntax is a unique language of its own that doesn't support normal Bash expressions, so it integrates poorly with the rest of the shell. The MSH regexp switch syntax is a highly effective way to integrate support for regular expression matching into the shell itself without necessitating other syntactic sacrifices.

In languages like Ruby, regular expressions are syntactic elements like strings or integers and they can be used in other kinds of transient expressions. MSH allows you to create a regular expression instance from a string, but regular expressions are not part of the core language.

MSH provides many syntactic mechanisms for regular expression matching and transformation with strings, so arguably, a Ruby-style regular expression type is not needed. MSH provides a -match operator for regular expression comparisons:

msh> "test5" -match "test[3-9]+"
msh> "test1" -match "test[3-9]+"

The -match operator can also be used in if and where statements:

msh> get-childitem | select extension | where { $_.extension -match ".*t" }

MSH also has a -nomatch operator, which will return False if the string matches the regular expression. By default, the -match and -nomatch operators are case-insensitive. To perform case-sensitive regular expression comparisons, you can use the -cmatch and -cnomatch operators. MSH also has operators that enable users to perform glob matches. For those who don't know, a glob is a pattern specification that uses a simplified regular expression syntax. The name comes from a Unix library function used to expand the patterns into filename matches. Yeah, you can insert the obligatory dyslexic blogger joke here. You can use -like anywhere you can use -match :

msh> get-childitem | select extension | where { $_.extension -like "*t" }

It doesn't make much sense to use a separate expression for that, since the get-childitem Cmdlet supports glob arguments by default:

msh> get-childitem *t | select extension

There are many cases where you will want to use the -like operator in your functions and Cmdlets to simulate the glob evaluation of the get-childitem Cmdlet.

Expand full story

You must to comment.

Need to register for a new account?

If you don't have an account yet it's free and easy.