Reputation: 95
Hopefully this question isn't already answered on the site. I want to replace every number in a string with that number and a space. So here's what I have right now:
"31222829" -replace ("[0-9]","$0 ")
The [0-9] looks for any numbers, and replaces it with that character and the space. However, it doesn't work. I saw from another website to use $0 but I'm not sure what it means.The output I was looking for was
3 1 2 2 2 8 2 9
But it just gives me a blank line. Any suggestions?
LardPies
Upvotes: 1
Views: 743
Reputation: 69
You can use a regex with positive lookahead to avoid the trailing space. Lookahead and lookbehind are zero-length assertions similar to ^
and $
that match the start/end of a line. The regex \d(?=.)
will match a digit when followed by another character.
PS> '123' -replace '\d(?=.)', '$0 '
1 2 3
To verify there's no trailing space:
PS> "[$('123' -replace '\d(?=.)', '$0 ')]"
[1 2 3]
Upvotes: 0
Reputation: 437618
tl;dr
PS> "31222829" -replace '[0-9]', '$& '
3 1 2 2 2 8 2 9
Note that the output string has a trailing space, given that each digit in the input ([0-9]
) is replaced by itself ($&
) followed by a space.
As for what you tried:
"31222829" -replace ("[0-9]","$0 ")
While enclosing the two RHS operands in (...)
doesn't impede functionality, it's not really helpful to conceive of them as an array - just enumerate them with ,
, don't enclose them in (...)
.
Generally, use '...'
rather than "..."
for the RHS operands (the regex to match and the replacement operand), so as to prevent confusion between PowerShell's string expansion (interpolation) and what the -replace
operator ultimately sees.
Case in point: Due to use of "..."
in the replacement operand, PowerShell's string interpolation would actually expand $0
as a variable up front, which in the absence of a variable expands to the empty string - that is why you ultimately saw a blank string.
Even if you had used '...'
, however, $0
has no special meaning in the replacement operand; instead, you must use $&
to represent the matched string, as explained in this answer.
To unconditionally separate ALL characters with spaces:
Drew's helpful answer definitely works.
Here's a more PowerShell-idiomatic alternative:
PS> [char[]] '31222829' -join ' '
3 1 2 2 2 8 2 9
Casting a string to [char[]]
returns its characters as an array, which -join
then joins with a space as the separator.
Note: Since -join
only places the specified separator (' '
) between elements, the resulting string does not have a trailing space.
Upvotes: 2
Reputation: 4020
This probably isn't the right way to do it, but it works.
("31222829").GetEnumerator() -join " "
The .GetEnumerator
method iterates over each character in the string
The -join
operator will then join all of those characters with the " "
space
Upvotes: 2