Как использовать реговое выражение в power shell

Information is power, and knowing how to sift through data quickly is a vital IT skill.

How to work with lookaheads and lookbehinds

In regular expressions, lookaheads and lookbehinds — collectively referred to as lookarounds — confirm characters before or after a match without including that text as part of the match.

For example, when using a regular expression to search a PowerShell script to find all variable names without matching on the dollar sign, you use a lookbehind to tell the regular expression that there must be a dollar sign in front of the string but not to include it in the match.

The lookaround syntax is straightforward:

  • Positive lookahead: ()
  • Negative lookahead: ()
  • Positive lookbehind: ()
  • Negative lookbehind: ()

This example uses a positive lookbehind, and the regular expression inside the lookbehind is . Since the dollar sign is a special character in regular expressions, you need to use a backslash for the escape, which means you want to match the literal character, not its special meaning in the context of regular expressions.

To use this on a PowerShell script, pipe its contents to the Select-String cmdlet:

positive lookbehind
Use a positive lookbehind in a PowerShell regular expression to find the variables without matching on the dollar sign in the variable name.

How to use the operator

There’s a good reason why I wouldn’t just match on the dollar sign and skip the confusing lookbehind. One of the powerful uses for regular expressions is to replace text. Lookbehinds help control the match when using groups in a regex replace expression to rearrange data.

For example, if you wrote a script but then learned it was not ideal to use on the right side of a conditional statement, then you will need to swap from the right side to the left side of the conditional statements. You can write a regular expression to match comparisons that use on the right side on the operator:

Here’s a breakdown of the regular expression:

  • — This checks for an if or while statement followed by a space or not and then an opening parenthesis. Regular expressions are case-sensitive, so this would only match on lowercase if and while statements.
  • (?<exp>.*) -eq \$null — The matches any character sequence and assigns it to the named group. That is followed by the operator and then . It is complicated to write a regular expression to account for any possible expression on the left side of the conditional statement, but it would be possible via PowerShell Abstract Syntax Tree instead of a regular expression.
  • — This is a positive lookahead that checks for the closing parenthesis.
:/>  Встроенный брандмауэр windows 7

Understanding the reason for lookarounds in this context requires learning how to work with the operator. You use in PowerShell to swap text based on a regular expression. You don’t have to worry about replacing the if, while or parenthesis since the lookarounds contain them. Focus on the matched conditional statements.

Next, use to exchange the conditional statements with their opposite:

-replace operator swap
The regular expression uses the -replace operator to swap the conditional statements in the code without altering the rest of the script.

The output shows the swapped conditional statements. By using lookarounds, the if statements stayed intact.

How to work with the operator

Another place that lookarounds come in handy is with the operator, which separates a string based on a regular expression. If you use a lookaround, you then can match on your pattern without splitting on too many characters.

To use a phone number example, take our normalized phone numbers, and split them into the area code and phone number. This means splitting them on the hyphen but only on the first hyphen that is preceded by a closing parenthesis.

For reference, here is the phone number format:

'(123)-456-7890'

This regular expression matches on a hyphen preceded by a closing parenthesis.

is the lookbehind to check for a closing parenthesis, and matches on the hyphen.

'(123)-456-7890' -split '(?<=\))-'

Advanced regular expressions give many ways to solve a problem

Here’s our example string:

'Hello, my name is "Anthony" and I am the author.'

Two regular expressions would work here:

Both deliver the desired data. You could use a combination for a better regular expression:

This returns the name between the quotes as shown in the screenshot.

The takeaway is there is no single right way to construct a regular expression.

It helps to know your way around lookarounds

While lookarounds may seem a bit esoteric, they do have their place in regular expressions, especially when it comes to working with the and operators. If you use regular expressions enough, there comes a time when knowing how to work with a lookaround comes in handy.

A regular expression is a series of characters that determine a matching pattern in text to find or replace input validation. Walk through a regex example in PowerShell.

Trying to find specific information within text or input can be a nightmare. Luckily, there is a way to simplify this process.

:/>  Windows ntp synchronization

Regular expressions (regex) consist of a sequence of characters that collectively define a pattern that is to be matched. For example, regular expressions are commonly used as a means for validating input or for locating specific information within a long string of text. Regular expressions can also be used as a means of performing string manipulation.

Regex is not PowerShell-specific. Most modern programming languages natively support the use of regular expressions.

  • An asterisk — * — is is a wildcard; it represents any individual character.
  • Brackets — [] — indicate that a character must match the characters enclosed in brackets. For example, [abc] indicates that the character must be A, B or C.
  • A caret symbol within brackets — [^] — works opposite from normal bracketed characters. Rather than declaring that a character must match those characters appearing in brackets, the caret indicates that a character cannot match any of the bracketed characters. If you were validating input and wanted to make sure that the letters A, B or C were not entered, you could use [^abc].

The examples of ways you can use regular expressions are simple and a little silly, but you can apply the approach as you need to.

Data extraction

In a PowerShell script, regular expressions enable you to locate and extract data. For example, you might create a script that locates specific data within a log file or one that extracts information from a webpage.

To show how you can use regular expressions for data extraction, I created a text file called SampleParagraph.txt. That text file contains my name and contact information, as well as the first few paragraphs of this article — as I would deliver it to the editor.

It’s simple to create a PowerShell script that reads a text file and looks for a string — in this case, an email address — within that file. You don’t even need to use regular expressions to accomplish such a task. You could locate a specific email address by using this command:

Select-String -Path SampleParagraph.txt -Pattern '<email address>'

If you look at Figure 1, you can see that this command has located my email address in the second line of the file.

:/>  Легко меняем формат (расширение) файла вручную
Search a text file using the Select-String command.
Figure 1. Use the Select-String command to search a text file.

You do not need regular expressions to locate data within a text file; they become useful in situations where you don’t know the exact text that you need to extract. I could use regex if the sample file contained an email address and I needed to find it but I didn’t know what the email address was. In that situation, using the previous command doesn’t work because there is no literal value — a specific email address — that I can search for.

Select-String -Path SampleParagraph.txt -Pattern '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'

As you can see, the first portion of the command is identical to what I used before. The difference is that, rather than searching for a literal value, I am searching for a pattern. Although the pattern looks cryptic, it has meaning.

The that comes at the beginning of the pattern tells PowerShell that the match should occur at a word boundary. This essentially means that any matches should happen at the beginning or end of a word.

PowerShell can identify an email address with regex.
Figure 2. PowerShell can find an email address using regex.

Input validation

$Email=Read-Host "Please enter an email address"
If ($Email -Match '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}')
{
Write-Host "This looks like an email address"
}
Else {
Write-Host "Invalid Email Address"
}
Validate the input with regex.
Figure 3. Use regex to validate input.

String manipulation

Just as you can use regular expressions to validate strings, you can also use them to manipulate them. There are countless uses for string manipulation. Consider how you might use string manipulation in conjunction with input validation. In some cases, if you detect invalid input, you might be able to use string manipulation to automatically correct it.

For example, my first name has a somewhat unusual spelling: Brien, rather than Brian. As you can imagine, my name gets misspelled a lot. The two most common misspellings are Brian and Brain. Here’s a simple PowerShell script that checks for these two misspellings and corrects them:

$Name=Read-Host "Please type Posey's first name"
If ($Name -Match "Br[ia][ia]n")
     {
     $Name='Brien'
     Write-Host "The name's spelling has been corrected to " $Name
     }
Else
     {
     Write-Host "The name was spelled correctly"
     }
The script will correct the input if necessary.
Figure 4. The script validates input and corrects the input if necessary.

Dig Deeper on IT operations careers and skills