0

Is there a Powershell regex command I could use to replace the last consecutive zero in a text string with a "M". For Example:

$Pattern = @("000123456", "012345678", "000000001", "000120000")

Final result:

00M123456
M12345678
0000000M1
00M120000

Thanks.

1 Answer 1

6

Search for the following regex:

"^(0*)0"

The regex searches for a consecutive string of 0 at the beginning ^ of the string. It captures all the 0 except the one for replacement. "^0(0*)" also works, since we only need to take note of the number of 0 which we don't touch.

With the replacement string:

'$1M'

Note that $1 is denotes the text captured by the first capturing group, which is (0*) in the regex.

Example by @SegFault:

"000120000" -replace "^(0*)0", '$1M'
Sign up to request clarification or add additional context in comments.

3 Comments

Would the line read "$Pattern | ForEach-Object {$_ -replace "^(0*)0", "$1M""? Thanks. Sorry, I'm not too familiar with regex, but I thought that would be the way to go.
@atownson: Sorry, but I am unfamiliar with PowerShell. I know PowerShell uses .NET regex and can write a regex, but I can't write PowerShell command to do it.
This answer is good, but use single quotes for the replacement string in powershell. "000120000" -replace "^(0*)0",'$1M' for example.

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.