Igor Kuznetsov
Igor Kuznetsov

Reputation: 415

Powershell regex broken

There is some string (its always should be . at the end)

$A = 'Send email to: [email protected].' 

Also there is code that as i understand should delete everything but email

(([regex]'Send email to:(.*?)\.').Match($A).Value -replace "Send email to: |\.") -replace ";$"

Problem is that code broken and it make

mail@domain 

instead of

[email protected]

how can it be fixed and what is the meaning of ";$" ?

Upvotes: 1

Views: 78

Answers (2)

js2010
js2010

Reputation: 27473

How about deleting what you don't want? $ means the end of the line. . means any character, so it needs escaping with a \. No second argument to -replace implies replacing it with $null, or deleting it. You can put multiple -replace operators together. Check out https://regex101.com to try out regex patterns.

$A -replace 'Send email to: ' -replace '\.$'

[email protected]

Or with the | or symbol:

$A -replace 'Send email to: |\.$'

[email protected]

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163362

You might make the match a bit more specific by capturing an email like format in the group and match the trailing dot.

In the replacement use group 1 $1

\bSend email to: ([^@\s]+@[^\s@]+\.[^\s@.]+)\.
  • \bSend email to: Match literally preceded with a word boundary
  • ( Capture group 1
    • [^@\s]+ Match 1+ times any char except @ or a whitespace char
    • @[^\s@]+ Match the @ followed by same as previous pattern
    • \.[^\s@.]+ Match the . followed by same as previous pattern
  • )\. Close group and match a dot

Regex demo | Try it online

For example

$A = 'Send email to: [email protected].'
$A -replace 'Send email to: ([^@\s]+@[^\s@]+\.[^\s@.]+)\.','$1'

Output

[email protected]

Upvotes: 1

Related Questions