Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Find 16digit number and mask particular position using regular expression

 
K.Suresh Kumar
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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})
Mask : $3***********$5
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.

Please help me to find out the correct way.

Thanks,
Suresh Kumar
 
Rob Spoor
Sheriff
Pie
Posts: 20552
57
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

Your mask therefore becomes $1***********$3
 
Winston Gutkowski
Bartender
Pie
Posts: 10430
63
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob Spoor, That regular expression worked well.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic