Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string into an array on every newline?

Tags:

powershell

In my situation, I will have a string that looks like this.

$emailList = "[email protected]
              [email protected]
              [email protected]"

How can I port this into an array with no white-space so it would look like

$emailList = @("[email protected]","[email protected]","[email protected]"
like image 242
R.Schulj Avatar asked Jul 12 '17 13:07

R.Schulj


People also ask

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can you split () by a newline Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by newline character in Python, pass the newline character "\n" as a delimiter to the split() function.

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.


1 Answers

Per the comments, if you do this:

($emailList -split '\r?\n').Trim()

It uses -split to separate the list in to an array based on the new line/return charaters and then .Trim() to remove any whitespace either side of each string.

Following this the result is now already an array. However if you explicitly want the output to be as a list of comma separated strings surrounded by double quotes you could then do this:

(($emailList -split '\r?\n').Trim() | ForEach-Object { '"'+$_+'"' }) -Join ','

Which uses ForEach-Object to add quote marks around each entry and then uses -Join to connect them with a ,.

like image 193
Mark Wragg Avatar answered Sep 25 '22 19:09

Mark Wragg