0

Having a text contains numbers; which regex expression to use to add numeric separators?

The separator character will be an underscore. Starting from the end, for every 3 digits there will be a separator.

Example input:

Key: 100000,
Value: 120000000000

Expected output:

Key: 100_000,
Value: 120_000_000_000

You can use any popular regex flavor (Perl, Pcre, Python etc.)

Ferit
  • 8,692
  • 8
  • 34
  • 59
  • 1
    Check this post: https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators – Mike67 Sep 20 '20 at 15:00
  • 2
    [`(?<=\d)(?=(?:\d\d\d)+\b)`](https://regex101.com/r/Tq7zYU/1/) will get the positions where to insert the underscore. – trincot Sep 20 '20 at 15:04
  • 1
    Strange dupe closure: this question here is programming-language agnostic, and the "dupe" is asking about how to do the formatting with Python code. – trincot Sep 20 '20 at 20:37
  • This is not a duplicate. That question is asking how to format in Python. This one is asking for a regex expression. – Ferit Sep 20 '20 at 21:27

2 Answers2

0

(?<=\d)(?=(?:\d\d\d)+\b) will get the positions where to insert the underscore.

Then it is just a matter of injecting the underscore, which is a non-regex task. For instance in JavaScript it would be:

let regex = /(?<=\d)(?=(?:\d\d\d)+\b)/g
let inputstr = `Key: 100000,
Value: 120000000000`;
let result = inputstr.replace(regex, "_");
console.log(result);

And in Python:

import re
regex = r"(?<=\d)(?=(?:\d\d\d)+\b)"
inputstr = """Key: 100000,
Value: 120000000000""";
result = re.sub(regex, "_", inputstr)
print(result)
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Regular expressions are used to find patterns in a string. What you do with the matches are language specific.

The regular expression pattern to find three numbers is pretty simple: /\d{3}/

Apply that expression to your specific language to retrieve the matches and build your desired output string:

Perl, using split and then join:

$string = "120000000000"
$new_string = join('_', (split /\d{3}/, $string))
# value of $new_string is: 120_000_000_000

PHP, using split and then join:

$string = "120000000000"
$new_string = implode ("_", preg_split("/\d{3}/", $string))
# value of $new_string is: 120_000_000_000

VB, using split and then join:

Dim MyString As String = "120000000000"
Dim new_string As String = String.Join(Regex.Split(MyString, "\d{3}"), "_")
'new_string value is: 120_000_000_000
Drew
  • 4,215
  • 3
  • 26
  • 40