Using Regex with Powershell |
|
https://technet.microsoft.com/en-us/magazine/2007.11.powershell.aspx
A (.) period matches one instance of any character.
A (?) question mark matches zero or one instance of any character.
Regex also recognizes the * and + symbols as repeaters. These need to follow some character or characters.
The * matches zero or more of the specified characters, while the + matches one or more of the specified characters.
What if you need to match the period, *, ?, or + symbols themselves? You simply precede them with a backslash, which is the regex escape character:
A character class is a broader form of wildcard, representing an entire group of characters. Windows PowerShell recognizes quite a few character classes. For instance:
^ anchors your regex for the beginning of the expression
$ anchors your regex for the ending the expression
Here is my example.
I need to return rows that have this pattern in the line "Ashburn, VA".
So double quotes, characters, coma, space, characters and finally double quotes
I have placed the CSV file into a variable with the get-content cmdlet.
I then pipe that to a where-object
$CSVfile = get-content c:\somefile.csv
$CSVfile | ?{$_ -match '^*\",\s*\"*'}
A (.) period matches one instance of any character.
A (?) question mark matches zero or one instance of any character.
Regex also recognizes the * and + symbols as repeaters. These need to follow some character or characters.
The * matches zero or more of the specified characters, while the + matches one or more of the specified characters.
What if you need to match the period, *, ?, or + symbols themselves? You simply precede them with a backslash, which is the regex escape character:
A character class is a broader form of wildcard, representing an entire group of characters. Windows PowerShell recognizes quite a few character classes. For instance:
- \w matches any word character, meaning letters and numbers.
- \s matches any white space character, such as tabs, spaces, and so forth.
- \d matches any digit character
^ anchors your regex for the beginning of the expression
$ anchors your regex for the ending the expression
Here is my example.
I need to return rows that have this pattern in the line "Ashburn, VA".
So double quotes, characters, coma, space, characters and finally double quotes
I have placed the CSV file into a variable with the get-content cmdlet.
I then pipe that to a where-object
$CSVfile = get-content c:\somefile.csv
$CSVfile | ?{$_ -match '^*\",\s*\"*'}