Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex – Group string with space

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you very much.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading