正则表达式在特定位置添加空格 [英] regex to add spaces in specific places

查看:40
本文介绍了正则表达式在特定位置添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 14 位长的数字,我需要将其拆分为以下格式:

I have a 14 digits long number that I need to split into this format:

xxx xxx xxx xxxxx

我有一个从末尾开始每 3 个字符拆分的正则表达式(因为前瞻?)

I have a regex that splits every 3 characters starting from the end (because of the lookahead?)

(?=(\d{3})+(?!\d))

这给了我:

xx xxx xxx xxx xxx

我尝试在 regex101.com 中使用lookbehind,但出现模式错误...

I tried using lookbehind in regex101.com but I get a pattern error...

(?<=(\d{3})+(?!\d))

如何使用lookbehind使其从字符串的开头开始(如果这是我的问题)以及如何仅重复该模式3次然后切换到\d{5} ?

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

推荐答案

试试这个:

(\d{3})(\d{3})(\d{3})

并替换为:

"$1 $2 $3 "

Regex 101 演示

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

这篇关于正则表达式在特定位置添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆