Skip to content

Instantly share code, notes, and snippets.

@orangexception
Created October 23, 2012 19:56
Show Gist options
  • Save orangexception/3941158 to your computer and use it in GitHub Desktop.
Save orangexception/3941158 to your computer and use it in GitHub Desktop.
Regular Expression to Insert Character after every X Characters

Regular Expression to Insert Character after every X Characters

I had a simple problem today. I needed to validate some files, but all of the line breaks were missing. I was dealing with a fixed width format data. A quick regular expression later and I had readable data.

Here's a few examples to demo the idea.

Insert a line break after every 94 characters

Find (.{94}) Replace \1\n

Insert a comma after every 10 characters

Find (.{10}) Replace \1,

@razvanioan
Copy link

razvanioan commented Jul 9, 2020

And if you can use negative lookahead, it's nice to avoid adding as last character if applicable

(.{10})(?!$)

@ElonSatoshi
Copy link

If this isn't working for you, try $1 instead of \1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment