Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Find 16digit number and mask particular position using regular expression Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Find 16digit number and mask particular position using regular expression" Watch "Find 16digit number and mask particular position using regular expression" New topic
Author

Find 16digit number and mask particular position using regular expression

K.Suresh Kumar
Ranch Hand

Joined: Nov 21, 2007
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})
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

Joined: Oct 27, 2005
Posts: 19544
    
  16

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7064
    
  16

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


Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here
K.Suresh Kumar
Ranch Hand

Joined: Nov 21, 2007
Posts: 41
Thanks Rob Spoor, That regular expression worked well.
 
 
subject: Find 16digit number and mask particular position using regular expression
 
Similar Threads
find replace in file with regular expression
Java regular expressions for value ranges
How to mask string not conforming to a regular expression pattern
Finding Numeric value from String object
regular expression