I need a help to use or build a regular expression to mask alphanumeric with *.
I tried it with this expression, but it doesn't work correctly when it has zeros in the middle of the string:
(?<=[^0].{3})\w+(?=\w{4})
Live samples: https://www.regexplanet.com/share/index.html?share=yyyyf47wp3r
| Input | Output |
|---|---|
| 0001113033AA55608981 | 0001113*********8981 |
| 23456237472347823923 | 2345************3923 |
| 00000000090000000000 | 0000000009000***0000 |
| 09008000800060050000 | 09008***********0000 |
| AAAABBBBCCCCDDDDEEEE | AAAA************EEEE |
| 0000BBBBCCCCDDDDEEEE | 0000BBBB********EEEE |
The rules are:
- The first 4 that are not zeros, and the last 4 a must be displayed.
- Leading zeros are ignored, but not removed or replaced.
You can capture initial zeros and 3 alhpanumeric chars right after them in one group, the middle part into a second group, and then the last 4 alphanumeric chars into a third group, then only replace each char in the second group.
Here is an example (Java 11 compliant):
See the Java demo.
The regex matches
^- start of string(0*\w{4})- Group 1: zero or more0chars and then any four alphnumeric/underscore chars(.*)- Group 2: any zero or more chars other than line break chars (replace with\w*if you only allow "word" chars)(\w{4})- Group 3: four "word" chars$- end of string.Java 8 compliant version:
See the Java code demo online.
But you may just use