Question:
I am trying to regex out a date from a text file. This is the content:
Storage Manager
Command Line Administrative Interface – Version 7, Release 1, Level 1.4
(c) Copyright by Corporation and other(s) 1990, 2015. All Rights Reserved.Session established with server TSERVER: Windows
Server Version 7, Release 1, Level 5.200
Server date/time: 11/22/2016 15:30:00 Last access: 11/22/2016 15:25:00ANS8000I Server command.
I need to extract the date/time after server date/time. I have written this regex:
1 2 |
/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})/ |
This works perfectly in regex101. See example on https://regex101.com/r/MB7yB4/1
However, in Powershell it reacts different.
1 2 |
$var -match "([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})" |
gives
Server date/time: 11/22/2016 16:30:00 Last access: 11/22/2016
15:37:19
and
1 2 |
$var -match "([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})" |
gives nothing.
I am not sure why the match is not the same.
Thanks for any help!
Answer:
The -match
operator returns a boolean value showing if a match was found or not. Also, it sets the $matches
variable with the match data (the whole match and capture group values). You just need to access the whole match:
1 2 |
if($var -match '[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}') { $matches[0] } |
See Using -match
and the $matches
variable in PowerShell.
Note that there is no need escaping /
synmbol in Powershell regexps, since this character is not special, and regex delimiters (those outer /.../
as in JS, PHP regexp) are not used when defining a regular expression in Powershell.