1

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} ?

3
  • The best answer may be 'do not use regex for this'... A simple for-loop is probably much easier. Commented Jul 6, 2017 at 11:32
  • you can try this regex to check the final result regex101.com/r/3dltJm/4 (^\+|\d{3} |\d{5}$) Commented Jul 6, 2017 at 11:39
  • 1
    "How can I use lookbehind so that it starts from the begining of the string" -I don't think JavaScript Regex has the look behind feature. Commented Jul 6, 2017 at 11:49

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I looked into it too much it seems and forgot about substitution. Thanks.
2

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.

4 Comments

I suggest to use /([\d]{3}(?:\d{2}$)?)/. In my Test-Script preg_split() captured "34" at the End too. Thats why I added the ?: in the last Subpattern, so it does not get put in the Split-array.
@Bernhard I already updated it to stop using capture groups since they aren't actually used
I cannot make this work for my needs. It does select the right groups but how do you insert spaces between them? (and no, a for loop is definitely not the right way to do this)
You get all of the matches and then just join them with a space?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.