Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell: Can't Get RegEx to work on multiple lines

I am getting notes from a ticket that come in the form of:

[Employee ID]: 
[First Name]: Test
[Last Name]: User
[Middle Initial]: 
[Email]: 
[Phone]: 
[* Last 4 of SSN]: 1234

I’ve tried the following code to get the first name (in this example it would be ‘Test’:

    if ($incNotes -match '(^\[First Name\]:)(. * ?$)')
        {
            Write-Host $_.matches.groups[0].value
            Write-Host $_.matches.groups[1].value
        }

But I get nothing. Is there a way I can use just one long regex pattern to get the information I need? The information stays in the same format on every ticket that comes through.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How would I get the information after the [First Name]: and so on….

>Solution :

You can use

if ($incNotes -match '(?m)^\[First Name]: *(\S+)') {
    Write-Host $matches[1] 
}

See the regex demo. If you can have any kind of horizontal whitespace chars between : and the name, replace the space with [\p{Zs}\t], or some kind of [\s-[\r\n]].

Details:

  • (?m) – a RegexOptions.Multiline option that makes ^ match start of any line position, and $ match end of lines
  • ^ – start of a line
  • \[First Name]: – a [First Name]: string
  • * – zero or more spaces
  • (\S+) – Capturing group 1: one or more non-whitespace chars (replace with \S.* or \S[^\n\r]* to match any text till end of string).

Note that -match is a case insensitive regex matching operator, use -cmatch if you need a case sensitive behavior. Also, it only finds the first match and $matches[1] returns the Group 1 value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading