How to match a string if it does not contain something?

I have a PowerShell script that will get a list of all the files in a folder, and then (based on regular expression matches inside the Switch statement) will move each file to the specified folder (depending on the regular expression matching).

I have a problem with a specific list. A group of files (PDF files named after their part number) that start with "40" are moved to the specified folder.

The expression itself is just enough for me, the problem is that if the file contains _ol OR _ol_ , then it cannot be a match.

For example, the file names below should match:

 401234567.pdf 401234567a.pdf 401234567_a.pdf 401234567a_something.pdf 

The below below should NOT match:

 401234567_ol.pdf 401234567_ol_something.pdf 

Using the regex ^(?i)40\w+[^_ol].pdf$ is the closest I can get. He will deny 401234567_ol.pdf as a coincidence; however, it accepts 401234567_ol_something.pdf . Does anyone know how I can deny this as a coincidence?

+5
source share
3 answers

Use a negative forecast ahead:

 ^(?i)(?!.*_ol)40\w+\.pdf$ 

Watch the demo

Looking ahead (?!.*_ol) at the very beginning of the pattern check, if later there is no _ol in the line. If he is present, we have no correspondence. The point must be escaped to match the literal point.

+2
source

You can use a negative forecast in your regular expression. The following regex will match any string that does not contain _ol :

 ^((?!_ol).)*$ 

Demo

Note that you need to use the m (multi-line) modifier for a multi-line string.

+3
source

Just use the -notmatch statement with a template that matches what you want to exclude:

 Get-ChildItem 'C:\source' -Filter '*.pdf' | ? { $_.BaseName -notmatch '_ol(_|$)' } | Move-Item -Destination 'C:\destination' 

or -notlike operator (for better performance):

 Get-ChildItem 'C:\source' -Filter '*.pdf' | ? { $_.BaseName -notlike '*_ol' -and $_.BaseName -notlike '*_ol_*' } | Move-Item -Destination 'C:\destination' 
0
source

All Articles