This article introduces the use of regular expressions in PowerShell. The regular expressions of PowerShell are the same as those of Microsoft's other languages and are very convenient to use.
What is the regular expression itself? This article will not discuss it. Anyway, PowerShell still uses Microsoft's regular expression rules. You should have learned it when learning VB, ASP, C# and other languages. Let's only talk about how to use regular expressions in PowerShell.
First give a task, use PowerShell to find the letter string sandwiched in the number string in the d:\ file. The contents are as follows:
12
12aaa3
123bbb4
123ccc45
We want to find out aaa bbb ccc.
Go to the program first:
$file = Get-Content "d:\"
$reg = "\d+(?<alp>\w+?)\d+"
foreach($line in $file){
if($line -match $reg){
#$Matches[0];
$;
}
}
The following explains one by one:
1. Get-Content is to get the content of a file and assign it to the $file variable
2. $reg is a regular expression, but note that the paragraph "\w+?" in the brackets is not unfamiliar with the non-greedy matching of the alpha characters. The paragraph "?<alp>" has nothing to do with the regular expression itself. It is a variable that is convenient for PowerShell to get matching values in brackets. This sentence is a bit confusing. To put it simply, it creates a variable whose value is the value matched by the regular expression in parentheses, that is, the value matched by "\w+?". When we learned C# before, we knew to use [n] to get the values in brackets. The same is true here. If there are multiple brackets, you can set a variable for each bracket.
3. if($line -match $reg) determines whether the string complies with the regular expression, and the return value is $True or $False
4. $, this is the call to step 2, and the variable alp is used as a member variable of the $Matches object.
5. $Matches[0], the value of the complete string that matches, $ is the value in parentheses.
The use of regular expressions can basically meet the needs. But I will add something new later.