A regular expression is a way of using a pattern to describe some piece of data. Granted, coming up with the pattern can be time-consuming. But let’s see if our string challenge can help shed some light on the subject. If you recall I am starting with a string, presumably from some log.
- \S means get any non-whitespace character
- + means get one or more instances of the preceding, e.g. non-whitespace character
- , means a literal comma
- \s means a single whitespace
- \S+ is a repeat of the first part.
This is similar to what I came up with splitting in the previous article.
As before, I can now parse out the relevant part of the string.
The thing about regular expression patterns is that they float to match anywhere in the string, unless you use anchors. Or you can fine-tune your pattern
- \b indicates a word boundary which usually means there is a space before the character
- \w means an alphanumeric character
- {1} means exactly one of the preceding, e.g. alphanumeric, characters
- \. means a literal period. The period is a special regular expression character so I need to escape it with a \ so PowerShell treats it literally.
- \) means a literal parentheses. These too are special characters so if you mean a ) you need to escape it.
I can get the value from $matches.values. Still with me? Let’s spin your head a bit more and let me show you the REGEX object. This object starts out as a regular expression pattern.
- \( is a literal parantheses
- . means any single character
- means any preceding instance so .* is a way of saying every and anything
- \) is a literal parentheses
If you merely want to test and see if the pattern matches in the string you can do this.
As I did with –Match I can get the value and parse it.
As you can see it all comes down to the pattern.
Since I’ve already found a pattern that matches exactly what I want without any additional parsing, I might as well use that.
Or if you want to show off your head-spinning PowerShell skills, try this one-liner:
I know many Windows IT Pros are new to regular expressions and find them difficult, but like anything it simple takes practice. So the next time you are looking to parse some string for some nugget of information, see if regular expressions can make your life easier. But I strongly believe that if you want to be taken seriously as a PowerShell professional, then you need to develop at least some basic proficiency with regular expressions. We’ll wrap up this mini-series next time with another aspect of regular expressions – named captures.
Source
No comments:
Post a Comment