Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Find 16digit number and mask particular position using regular expression

K.Suresh Kumar
Ranch Hand
Posts: 41
Hi,

I am trying to find 16 digit number in given string and mask first & last two position of 16 digit number using regular expression.
My Code:

Regular Expression : ((\\W)+([0-9]{2}))+([0-9]{12})+([0-9]{2})
String : jhjhjhj005234567890123456 789 09 232323 34567890123456 2345678901234 5012303420560312 5043309820105604gggb 5043302320543215"

Output
jhjhjhj005234567890123456 789 09 232323 34567890123456 234567890123450***********1250***********04gggb50***********15

Problem : I don't want to mask this 5043309820105604gggb string.

Thanks,
Suresh Kumar

Rob Spoor
Sheriff
Posts: 20665
65
• 1
Use a negative lookahead that prohibits a word character after the number: (?!\w). This will not be part of the match. In fact, you should use a negative lookbehind as well; right now you cut off all those spaces. The entire regex becomes (?<!\w)([0-9]{2})+([0-9]{12}+([0-9]{2})(?!\w). You now have four groups:
0: the entire match
1: the first two digits
2: the next twelve digits
3: the last two digits

Winston Gutkowski
Bartender
Posts: 10527
64
K.Suresh Kumar wrote:I am trying to find 16 digit number in given string and mask first & last two position

Hmmm. I wonder why?

Problem : I don't want to mask this 5043309820105604gggb string.

Then you need to explain why not (to yourself as much as us). Rob's suggestion is a good one, but he has assumed that a word break is the reason. If it isn't, you need to let us know.

Winston

K.Suresh Kumar
Ranch Hand
Posts: 41
Thanks Rob Spoor, That regular expression worked well.