4

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?.

1
  • You could use [regex]::Split($temp, '##[^;]*;'), too, but you'd need to remove leading/trailing '##[^;]*;' to get rid of empty values. Commented May 31, 2016 at 9:50

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.