拥有一个包含数字的文本;使用哪个正则表达式添加数字分隔符?
分隔符将是下划线。从末尾开始,每3位数字将有一个分隔符。
示例输入:
Key: 100000,
Value: 120000000000
预期输出:
Key: 100_000,
Value: 120_000_000_000
您可以使用任何流行的regex风格(Perl、Pcre、Python等(
(?<=d)(?=(?:ddd)+b)
将获得插入下划线的位置。
然后只需要注入下划线,这是一项非正则表达式任务。例如,在JavaScript中,它将是:
let regex = /(?<=d)(?=(?:ddd)+b)/g
let inputstr = `Key: 100000,
Value: 120000000000`;
let result = inputstr.replace(regex, "_");
console.log(result);
在Python中:
import re
regex = r"(?<=d)(?=(?:ddd)+b)"
inputstr = """Key: 100000,
Value: 120000000000""";
result = re.sub(regex, "_", inputstr)
print(result)
正则表达式用于查找字符串中的模式。你对比赛的处理是特定语言的。
找到三个数字的正则表达式模式非常简单:/d{3}/
将该表达式应用于您的特定语言以检索匹配项并构建所需的输出字符串:
Perl,使用拆分然后连接:
$string = "120000000000"
$new_string = join('_', (split /d{3}/, $string))
# value of $new_string is: 120_000_000_000
PHP,使用拆分然后加入:
$string = "120000000000"
$new_string = implode ("_", preg_split("/d{3}/", $string))
# value of $new_string is: 120_000_000_000
VB,使用拆分然后连接:
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