Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the PowerShell match operator

Version: PowerShell 2.0

I have the following:

$pattern = '^.\d_\d\d\d\d\d\d\d\d_\d\d\d\d\d\d\d\d\d\d\d\d\d\d.pdf$'
$filename = '123456_12345678_12345678901234.pdf'
$filename -match $pattern

I want the ^ and $ characters to start and end the string. Since I'm using the wild card '.' in the beginning, I really just care about the $ terminator. These characters do not appear to work as I expect in PowerShell because the above code returns FALSE.

What pattern will return true for $goodname, but false for $badname. The number of digits in the first segment of the name is unknown.

$goodname = '123456_12345678_12345678901234.pdf'
$badname = '123456_12345678_12345678901234.pdf.hold'
like image 766
Derik Avatar asked Nov 22 '25 17:11

Derik


1 Answers

It returns false because the filename does not match the pattern.

A better regex would be:

$pattern = '^\d+_\d{8}_\d{14}\.pdf$'
$filename = '123456_12345678_12345678901234.pdf'
$filename -match '\d{6}_\d{8}_\d{14}\.pdf.*'

Explanation

  • ^ At the start of the string
  • \d+ Match at least one digit (as you said the number of digits here is unknown)
  • _ Match an underscore
  • \d{8} Match 8 digits
  • _ Match an underscore
  • \d{14} Match 14 digits
  • \. Match a dot .
  • pdf Match "pdf"
  • $ And don't match if you are not now at the end of the string.
like image 118
RB. Avatar answered Nov 25 '25 10:11

RB.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!