regex matching help in Powershell scripting

Wether $user = Samson, Tom or $user = Samson, V Tom, I still get "ya'll got a middle name"
What is wrong with my regex for my third match attempt?


$user = "Employee Name: Samson, V Tom"
$user -match "Employee Name: (\w+)"
echo $matches[1]
$1 = $matches[1]
echo $1
$user -match "Employee Name: \w+, (\w+)"
echo $matches[1]
$2 = $matches[1]
echo $2
$user -match "Employee Name: \w+, \w+ (\w+)"
echo $matches[1]
$3 = $matches[1]
echo $3
if ($3) { echo "ya'll got a middle name"} else { echo "ya'll ain't got no middle name" }

Open in new window

LVL 3
_-W-_Asked:
Who is Participating?
 
ToddBeaulieuConnect With a Mentor Commented:
You're still not checking the result of -match operation. If it's false, it doesn't make sense to look at the matches collection.
0
 
ToddBeaulieuCommented:
The parens group the last match, which is the last name. So "Samson, V Tom" gives you "Tom". If you move the parens over to the middle match, you'll get "V" if there is a middle name.

If you remove the middle name from the user, $user -match ... will return False, which you need to check for, instead of assuming the Matches collection holds the answer. If you run the above, change the name and re-run it, the matches collection will still hold the previous results.
0
 
_-W-_Author Commented:
Hmm. This still did not work.. Am I checking $3 the wrong way? See code:
$1 = "hello"
$2 = "hello"
$3 = "hello"
$user = "hello"

$user = "Employee Name: Samson, Tom"
$user -match "Employee Name: (\w+)"
echo $matches[1]
$1 = $matches[1]
echo $1
$user -match "Employee Name: \w+, (\w+)"
echo $matches[1]
$2 = $matches[1]
echo $2
$user -match "Employee Name: \w+, (\w+) \w+"
echo $matches[1]
$3 = $matches[1]
echo $3
if ($3) { echo "ya'll got a middle name"} else { echo "ya'll ain't got no middle name" }

Open in new window

0
 
käµfm³d 👽Commented:
When $user equals "Employee Name: Samson, Tom", your 3rd -match call returns false, and so matches[1] isn't updated. That group refers to the match of the 2nd -match call. Test the return of your 3rd -match call before trying to use the object:

$user = "Employee Name: Samson, Tom"
$user -match "Employee Name: (\w+)"
echo $matches[1]
$1 = $matches[1]
echo $1
$user -match "Employee Name: \w+, (\w+)"
echo $matches[1]
$2 = $matches[1]
echo $2
if ($user -match "Employee Name: \w+, \w+ (\w+)")
{
  echo $matches[1]
  $3 = $matches[1]
  echo $3
}

if ($3) { echo "ya'll got a middle name"} else { echo "ya'll ain't got no middle name" }

Open in new window

0
 
käµfm³d 👽Commented:
@ToddBeaulieu

My apologies...  I didn't read your first comment carefully. I see you already mentioned what I restated  : \
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.