JavaScript RegEx: Format string with dynamic length to block format

前端 未结 3 1284
情深已故
情深已故 2021-01-21 08:45

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

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

RegEx:



        
3条回答
  •  春和景丽
    2021-01-21 09:07

    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 Demo

    Lookbehind:

    • (?<=: 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
    • ): End assertion

    Lookahead:

    • (?=\d+$): Make sure we have at least a digit ahead

提交回复
热议问题