Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for replacing first 5 numbers, irrespective of anything between them?

I'm trying to achieve the following match

Input

123-45-6789
123456789
1234

Reg Ex(s) Tried with output:

\d{5}

123-45-6789

123456789

1234

\d{2,3}

123-45-6789

123456789

1234

\d{3}-{0,1}\d{2}

123-45-6789

123456789

1234

I need to supply this regex to replace method, and I don't want the "-" to be replaced, it should only replace the first 5 digits without changing the format:

Expected Output

123-45-6789

123456789

1234

EDIT

In the above sample outputs:

1> all are matched with global regex 2> the bolded digits are only expected to be matched

The Purpose

I need to mask SSN, eg: 444-55-6666 becomes ###-##-6666 and 444556666 becomes #####6666. Without hampering the format.

like image 986
Abhi Avatar asked Jul 24 '17 08:07

Abhi


People also ask

How does regex Match 5 digits?

match(/(\d{5})/g);

What does replace (/\ d G do?

replace(/\D/g, ''); which removes all non-digit characters, including the "." What do I need to do to keep that?

How do you substitute in regex?

Match a white space followed by one or more decimal digits, followed by zero or one period or comma, followed by zero or more decimal digits. This is the first capturing group. Because the replacement pattern is $1 , the call to the Regex. Replace method replaces the entire matched substring with this captured group.

How do I match a range of numbers in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.


2 Answers

You want to match and replace those first five digits:

var str = `123-45-6789
123456789
1234
`
console.log(str.replace(/^(\D*\d\D*){5}/gm, function(match) {
    return match.replace(/\d/g, '*');
}))
like image 83
revo Avatar answered Oct 19 '22 15:10

revo


Here's other ways of looking at it:

  • You want to ignore all non-numeric characters, and then get the first five numbers

    input.replace(/\D/g,'').substr(0,5);
    
  • You want to match five numeric characters, wherever they may appear in the input

    input.match(/\d/g).slice(0,5);
    

There is almost always more than one way to approach a problem. If you can't figure out how to do what you want, try re-wording the problem until you find something you can do.

like image 41
Niet the Dark Absol Avatar answered Oct 19 '22 16:10

Niet the Dark Absol