Home > Software design >  Regex - Group string with space
Regex - Group string with space

Time:03-30

I need to group a string into groups of 3 characters.

Examples:

In: 900123456 -> Out: 900 123 456
In: 90012345  -> Out: 900 123 45
In: 90012     -> Out: 900 12

Is there any way to do this with regex?

Thank you very much.

CodePudding user response:

Have a go with /\d{3}(?!\b)/gm as pattern and $0 as replacement.

Explanation:

  • \d to match a digit. But we want 3 of them so it becomes \d{3}.
  • we would like to replace the match by itself followed by a space. But we should not do that if it is at the end of the line because we don't want to add a trailing space. This can be avoided with a negative lookahead to search for a word boundary with \b. This becomes (?!\b) for the negative lookahead.

You can test it here: https://regex101.com/r/MIQnF3/1

let input = document.getElementById('input');
let output = document.getElementById('output');

// In JS I had to capture the 3 digits in a group since $0 did not work.
let pattern = /(\d{3})(?!\b)/gm;

output.innerHTML = input.innerHTML.replace(pattern, '$1 ');
<p>Input:</p>
<pre><code id="input">900123456
90012345
90012</code></pre>

<p>Output:</p>
<pre><code id="output"></code></pre>

  • Related