user3127554
user3127554

Reputation: 577

The string is not a valid regular expression

I have a folder with DNS .zone files.

I'm trying to return all files and the string that have an IP address that looks like 172.20.*.

I use the following:

Get-ChildItem -Recurse -Path 'C:\Root' | Select-String -Pattern '*172.20.*' | group | select name

but this returns:

Select-String : The string *172.20.* is not a valid regular expression: parsing "*172.20.*" - Quantifier {x,y} following nothing.

I tried using the -SimpleMatch case in my Select-String without success. Enclosing the string in double quotes is also not working.

If I use actual text as my pattern, it works without a problem.

Where is my problem?

Upvotes: 3

Views: 3961

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200373

Like the error message says: *172.20.* is not a valid regular expression. It's a wildcard pattern, which can be used with the -like operator, but not with Select-String. * in a regular expression is a modifier that cannot stand by itself, it requires something that it applies to. The regular expression equivalent of a wildcard * (match zero or more characters) is .*. But since regular expressions (unlike wildcard patterns) are not anchored by default, you don't need to add them at the beginning and end of your pattern for the match to work.

Either change your expression to an actual regular expression:

... | Select-String -Pattern '172\.20\.' | ...

or modify your code to use wildcard matches instead of regular expression matches:

Get-ChildItem -Recurse  -Path 'C:\Root' | Where-Object {
    Get-Content $_.FullName | Where-Object { $_ -like '*172.20.*' }
} | Select-Object -Expand Name

Using -SimpleMatch did not work with your approach, because -Pattern '*172.20.*' -SimpleMatch would be looking for a literal (sub)string *172.20.* (with the asterisks), which probably isn't present in your files. It would have worked had you removed the wildcards from the pattern:

... | Select-String -Pattern '172.20.' -SimpleMatch | ...

Upvotes: 6

Related Questions