views:

327

answers:

3

How to extract the number in the string "Task(12345)" with Regular Expression and Powershell? I tried the following, but no chance.

$file = gc myfile.txt
$matches = ([regex]"Task\(\d{1,5}\)").matches($file)
# Get a list of numbers

Could someone please help me to find the correct regular expression?

Thanks, Martin

A: 

If you want exactly 5 digits in there you could use:

^Task\([\d{1,5}]{5}\)$

Otherwise for an arbitrary number of digits go with:

^Task\([\d{1,5}]+\)$
Gabriel Hurley
For the arbitrary number of digis, why not just ^Task\([\d+\)$ ?
Salty
It doesn't work. The Task number are a little bit every where in a source file.
Martin
+3  A: 

Do you want to get all occurances in the file? If so I would do the following

$r = "^Task\((\d+)\)$"
$res = gc myFile.txt | 
  ?{ $_ -match $r } |
  %{ $_ -match $r | out-null ; $matches[1] }
JaredPar
+2  A: 

Keep in mind that Select-String makes this a one-liner:

PS> Select-String 'Task\((?<num>\d{1,5})\)' myfile.txt | 
        %{$_.matches[0].Groups['num'].value}