gyc
gyc

Reputation: 4360

regex to add spaces in specific places

I have a 14 digits long number that I need to split into this format:

xxx xxx xxx xxxxx

I have a regex that splits every 3 characters starting from the end (because of the lookahead?)

(?=(\d{3})+(?!\d))

Which gives me:

xx xxx xxx xxx xxx

I tried using lookbehind in regex101.com but I get a pattern error...

(?<=(\d{3})+(?!\d))

How can I use lookbehind so that it starts from the begining of the string (if that's my issue) and how can I repeat the pattern only 3 times and then switch to a \d{5} ?

Upvotes: 1

Views: 413

Answers (2)

Nick Chapman
Nick Chapman

Reputation: 4624

You can use something like so: https://regex101.com/r/yqmyvs/3

The regex for this being:

(?:\d{3})(?:\d{2}$)?

This basically says: I want groups of three numbers, unless it's the end of the string in which case I want 5.

Though, as commented on your question, this isn't really something you would normally use regex for.

Upvotes: 2

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

Try this:

(\d{3})(\d{3})(\d{3})

and replace by this:

"$1 $2 $3 "

Regex 101 demo

const regex = /(\d{3})(\d{3})(\d{3})/g;
const str = `12345678901234`;
const subst = `$1 $2 $3 `;
const result = str.replace(regex, subst);
console.log( result);

Upvotes: 2

Related Questions