PowerShell regex script

Viewed 130

Have a list of usernames, they are formatted in one of two ways:

John Smith

John.Smith

I would like to get just the last name from each line in a text file.

I'm guessing I have to use a -replace or -remove command, just not sure how to format the regex.

I have this:

$source = "path\to\name\list.txt"

$final = "path\to\final\output.txt"

(Get-Content $source -Raw) -replace "^.\.|^."", "" | Set-Content $final

but it's not working.

2 Answers

Use

^[^\s.]+[\s.]+

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [^\s.]+                  any character except: whitespace (\n, \r,
                           \t, \f, and " "), '.' (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  [\s.]+                   any character of: whitespace (\n, \r, \t,
                           \f, and " "), '.' (1 or more times
                           (matching the most amount possible))

Another way is also possible:

^.*[\s.]

See another proof.

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  [\s.]                    any character of: whitespace (\n, \r, \t,
                           \f, and " "), '.'

I would simply use -split on whitespace (\s) or dot, take the last element of the resulting array.

Get-Content -Path $source | ForEach-Object {($_.Trim() -split '[\s.]')[-1]} | Set-Content -Path $final
Related