NathanK NathanK - 2 months ago 25x
Python Question

Replace leading zeros with spaces

I have a text file of multiple records. Each record has a field which has some number of leading zeros that I need to replace with that number of spaces. A record will look like this:

A206 000001204 X4609

I need the record to look like this:

A206 1204 X4609

I'm extremely unfamiliar with regex but the following regex seems to find the matches that I need:


However, I have no idea how to do the replacement. A ReplaceAll for Notepad++ would be awesome but I can also create a quick program in C#, Powershell, or Python if needed. Can anyone give me some pointers on the regex for this?


Yes, \b0+ would probably work.

Here using Regex.Replace() in C#:

using System.Text.RegularExpressions;

Regex.Replace(inputString, @"\b0+", m => "".PadLeft(m.Value.Length,' '));

The last argument to Replace() is a simple lambda function that returns a string of the same length as the number of matched 0s, but consisting only of spaces

You can do the same in PowerShell, substituting a scriptblock for the lambda function:

PS C:\> $inputString = 'A206   000001204   X4609'
PS C:\> [regex]::Replace($inputString, '\b0+', {param($m) ' ' * $m.Value.Length})
A206        1204   X4609