Printing the elements of list inline

Viewed 560

Suppose I have a list = [4, 1, 8, 3], I want to print all the elements of list in the same line like:

4 1 8 3

I checked this regular expression ^\[|,|\] on regexr.com and it selected everything except the elements. So I was expecting

print(list.toString().replaceAll('^\[|,|\]', ''));

to match above output, but it outputs:

[4, 1, 8, 3]

How do achieve the desired output?

Note that I cannot have whitespace around the output so something like this won't work:

list.forEach((element) => stdout.write('$element '));

Edit: I got it to work with

  print(list
      .toString()
      .replaceAll(',', '')
      .replaceAll('[', '')
      .replaceAll(']', ''));

is this the best that can be done?

2 Answers

Use the list.join(' '); method to print all the elements with a space joining them. This will not put a space at the front or the end either.

It's also useful for creating comma-separated lists.

list.join(', '); creates a string with a comma & space separating each element

NOTE: If you just need to "convert" a list of integers into a string of space-separated numbers, you just need to use list.join(" "). I understand you just practice regex and hence is my regex answer below.

You need to pass a RegExp compiled object to the .replaceAll to actually use a regex. Also, you need to use a raw string literal, or you will have to double your backslashes.

You can use

print(list.toString().replaceAll(new RegExp(r'^\[|,|\]'), ''));

Output: 4 1 8 3.

Note your regex is equal to ^\[|[,\]] that matches a [ at the start of string, or a comma or ] anywhere inside a string. You probably wanted to match ] only at the end of string, ^\[|,|]$.

Related