JavaScript RegEx:将具有动态长度的字符串格式化为块格式 [英] JavaScript RegEx: Format string with dynamic length to block format

查看:72
本文介绍了JavaScript RegEx:将具有动态长度的字符串格式化为块格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下RegEx格式将字符串赋予以下输出块模式:

The following RegEx formats given string to following output block pattern:

123 456 78 90 (= 3位3位2位2位)

123 456 78 90 (= 3 digits 3 digits 2 digits 2 digits )

RegEx:

string.replace(/^(\d{3})(\d{3})(\d{2})(\d{2})$/g, '$1 $2 $3 $4');

仅当给定的输入字符串与10位数字的确切长度匹配时,此示例才有效.

This example only works, if given input string matches exact length of 10 digits.

如何调整正则表达式以适应每个字符串长度?

How can I adjust the RegEx to work with every string length?

  • 1234->123 4
  • 1234567->123 456 7
  • 123456789->123 456 78 9
  • 1234567890123->123 456 78 90 12 3

背景:当用户输入数字时,我想直接设置表单输入字段的输入字符串的格式...

Background: I want to format the input string of a form input field directly, when a user enters the number...

推荐答案

在后面使用允许动态长度声明的现代Javascript后缀,您可以使用此正则表达式进行匹配:

Using modern Javascript lookbehind that allows dynamic length assertion, you can use this regex to match:

/(?<=^(?:\d{6}(?:\d{2})*|(?:\d{3}){1,2}))(?=\d+$)/g

只需将其替换为一个空格,即""

Just replace that with a single space i.e. " "

RegEx演示

隐藏:

  • (?< = :开始声明
    • ^(?:\ d {6}(?:\ d {2})* :确保我们后面有6位数字,后跟0或多个数字对
    • | :或
    • (?:\ d {3}){1,2}):让我们后面有一组或两组3位数字集
    • (?<=: Start assertion
      • ^(?:\d{6}(?:\d{2})*: Make sure we have 6 digits followed by 0 or more digits pair behind
      • |: OR
      • (?:\d{3}){1,2}): Make we have one or two sets of 3 digit sets behind

      提前提醒:

      • (?= \ d + $):确保我们至少有一位数字
      • (?=\d+$): Make sure we have at least a digit ahead

      这篇关于JavaScript RegEx:将具有动态长度的字符串格式化为块格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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