Regex match every occurrence

I want to match every occurrence of a pattern starting with date and ending with any numbers after the period. I saw a similar question on the Reddit PowerShell page, but no solution.

$string = '2020-01-01,John Doe,AddressOne,123456,23.23,2020-01-05,Jane Smith,AddressTwo,445538754,12.157'
[regex]::Matches($string, '\d{4}-.*\.\d{1,}')

I know this is correct because it gives 2 date values
[regex]::Matches($string, '\d{4}-\d{2}-\d{2}') 

Expected non-greedy results:
2020-01-01,John Doe,AddressOne,123456,23.23
2020-01-05,Jane Smith,AddressTwo,445538754,12.157

I googled the subject you used for this post with “PowerShell” in front of it and found this as the first hit. It might help you:

If not here is the complete search:

You have to make your regex non greedy … the following snippet works for the given example

$string = 
    '2020-01-01,John Doe,AddressOne,123456,23.23,2020-01-05,Jane Smith,AddressTwo,445538754,12.157'
Select-String -Pattern '\d{4}-\d{2}-\d{2}.+?\.\d+' -InputObject $string -AllMatches | 
Select-Object -ExpandProperty Matches |
Select-Object -Property Value

I see. My error was I put the question mark at the end of my pattern not before the period. This site gave a nice explanation and highlights my regex pattern differences. The following worked for me. I like to use the least amount of code possible and keep regular expression patterns as short as possible. Thanks for the help.

[regex]::Matches($string, '\d{4}-.+?\.\d+') 

Glad you found a working solution. :+1:t4:

I understand that and I agree most of the time when it’s about PowerShell code. :wink: But on the other hand that makes a regex pattern less specific and in a bad case depending on your input you may end up with a false positive.