Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write regular expression in powershell

I need regular expression in powershell to split string by a string ## and remove string up-to another character (;).

I have the following string.

$temp = "[email protected]## deliver, expand;[email protected]## deliver, expand;[email protected]## deliver, expand;"

Now, I want to split this string and get only email ids into new array object. my expected output should be like this.

[email protected]
[email protected]
[email protected]

To get above output, I need to split string by the character ## and remove sub string up-to semi-colon (;).

Can anyone help me to write regex query to achieve this need in powershell?.

like image 233
kombsh Avatar asked Mar 12 '23 03:03

kombsh


2 Answers

If you want to use regex-based splitting with your approach, you can use ##[^;]*; regex and this code that will also remove all the empty values (with | ? { $_ }):

$res = [regex]::Split($temp, '##[^;]*;') | ? { $_ }

The ##[^;]*; matches:

  • ## - double #
  • [^;]* - zero or more characters other than ;
  • ; - a literal ;.

See the regex demo

enter image description here

like image 150
Wiktor Stribiżew Avatar answered Mar 20 '23 07:03

Wiktor Stribiżew


Use [regex]::Matches to get all occurrences of your regular expression. You probably don't need to split your string first if this suits for you:

\b\w+@[^#]*

Regular expression visualization

Debuggex Demo

PowerShell code:

[regex]::Matches($temp, '\b\w+@[^#]*') | ForEach-Object { $_.Groups[0].Value }

Output:

[email protected]
[email protected]
[email protected]
like image 27
Martin Brandl Avatar answered Mar 20 '23 09:03

Martin Brandl