How about this?.
Removed to avoid confusion.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have multiple multiple line strings in the below format.
$p=@'
Name=James
Location=IN
PinCode:5000112
Dept=Sales
Employee:602389
'@
I want to extract only the Employee ID from the above string, however there is no specific index location for the Employee ID i.e. it can appear anywhere on the string and there is no specific delimiter for the Employee ID in the string. I am running the below command, however it is returning both the pin code and the employee id.
$p -replace '\D+([0-9]).','$1'
How can I only extract the employee id from any such string?
Similar to the answer @MotoX80 provided:
$p=@'
Name=James
Location=IN
PinCode:5000112
Dept=Sales
Employee:602389
'@
$e=""
if ($p -match 'Employee\:(\d+)'){
$e = $Matches[1]
}
Because the string contains multiple lines (each terminated by CrLf), each "line" is subjected to the regex. If the replace fails to match the regex the "line" is returned unaltered. Thus, you get the whole string contained in the $p variable.
Thanks for the answers. I also wanted to mention that sometimes in the String Employee is just mentioned as ID followed by the employee id and sometimes just the employee id is mentioned directly without any prefix.
The delimiter is also not the same always, it keeps changing.
In this case how can I extract the employee id.
Thanks for the answers. However I wanted to add that the delimiter is not always the same i.e. :
It keeps changing. Also sometimes the string mentions ID instead of Employee and sometimes there is no prefix given before the Employee ID. In such a case how can I extract only the Employee ID.
Is the employee id always numeric? (Updated.) And updated again to ensure that vertical bars surround the employee/id number. If you have any new string iterations to indicate that field, you will need to add in additional -replace statements to edit them out so that you have only the numeric id surrounded by the bars.
$p=@'
Name=James Smith
Location=IN
PinCode:5000112
Dept=Sales
Employee:602389
'@
$p2 = ($p.ToUpper() -replace "`n","|" -replace "`r","|" `
-replace "(EMP)([A-Z]*)", "" -replace "ID", "" `
-replace " ", "" -replace ":", "") + "|"
cls
$p2
$Matches.Clear()
$p2 -match "\|([0-9]+)\|"
$Matches
""
"ID=" + $Matches[1]