简体   繁体   English

格式化字符串并用正则表达式替换

[英]Format and replace a string with a regular expression

I have a number that's at least 7 digits long. 我的电话号码长度至少为7位数字。 Typical examples: 0000123 , 00001234 , 000012345 典型的例子: 000012300001234000012345

I want to transform them so that they become respectively: 01:23 , 12:34 , 23:45 我想改造他们,让他们分别变为: 01:2312:3423:45

Which mean replacing the whole string by the last 4 characters and putting a colon in the middle. 这意味着用最后四个字符替换整个字符串,并在中间放置一个冒号。

I can get the last 4 digits with (\\d{4})$ And I can get 2 groups with this: (\\d{2})(\\d{2})$ 我可以使用(\\d{4})$获得最后4位数字,并且我可以使用以下方式获得2组: (\\d{2})(\\d{2})$

With the last option, on a string 0000123 $1:$2 match gives me 00001:23 where I want 01:23 使用最后一个选项,在字符串0000123 $ 1:$ 2上匹配给我00001:23我想要的位置01:23

I replace the string like so: 我这样替换字符串:

newVal = val.replace(/regex/, '$1:$2');

You need to match the beginning digits with \\d* (or with just .* if there can be anything): 您需要用\\d* (或者如果有可能,只用.* )匹配起始数字:

 var val = "0001235"; var newVal = val.replace(/^\\d*(\\d{2})(\\d{2})$/, '$1:$2'); console.log(newVal); 

Pattern details : 图案细节

  • ^ - start of string ^ -字符串开头
  • \\d* - 0+ digits (or .* will match any 0+ chars other than line break chars) \\d* -0+个数字(或.*将匹配除换行符以外的任何0+个字符)
  • (\\d{2}) - Group 1 capturing 2 digits (\\d{2}) -组1捕获2位数字
  • (\\d{2}) - Group 2 capturing 2 digits (\\d{2}) -第2组捕获2位数字
  • $ - end of string. $ -字符串结尾。

As Alex K. said , no need for a regular expression, just extract the parts you need with substr : 正如Alex K.所说 ,不需要正则表达式,只需使用substr提取所需的部分:

val = val.substr(-4, 2) + ":" + val.substr(-2);

Note that when the starting index is negative, it's from the end of the string. 请注意,当起始索引为负数时,它是从字符串的末尾开始的。

Example: 例:

 function update(val) { return val.substr(-4, 2) + ":" + val.substr(-2); } function test(val) { console.log(val + " => " + update(val)); } test("0000123"); test("0001234"); test("000012345"); 

Use this regex: ^(\\d+?)(\\d{2})(\\d{2})$ : 使用此正则表达式: ^(\\d+?)(\\d{2})(\\d{2})$

 var newVal = "0000123".replace(/^(\\d+?)(\\d{2})(\\d{2})$/, '$2:$3'); console.log(newVal); 

您可以丢掉第一个字符,而仅替换最后一个匹配的部分。

 console.log('00000001234'.replace(/^(.*)(\\d{2})(\\d{2})$/, '$2:$3')); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM