Dreamer
Dreamer

Reputation: 7549

In java what is the regular expression to add mask to string with certian pattern

I am trying to get following strings:

8374651-37374-19283-284745800
928S-29ED374-872B34-932837
26598TA-297374-CND283-16373
82911-LD391DB-632D-4927831

Looks like this by java regex:

XXXXXXX-XXXXX-XXXXX-284745800
XXXX-XXXXXXX-XXXXXX-932837
XXXXXXX-XXXXXX-XXXXXX-16373
XXXXX-XXXXXXX-XXXX-4927831

and there is no pattern about the length of string between each hyphen.

It could be easy to replace everything except hyphen with X but really difficult to me to exclude last part.

Upvotes: 0

Views: 4241

Answers (3)

alpha bravo
alpha bravo

Reputation: 7948

or this pattern, replace w/ x

(?!-).(?=.*-)

Demo

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Use string.replaceAll function.

string.replaceAll("[^-\\n](?=.*?-)", "X");

This matches all the characters (but not of a hyphen) which was followed by a hyphen. It won't match the last part since it isn't followed by a hyphen.

DEMO

Upvotes: 2

vks
vks

Reputation: 67968

[^-\n](?=.*-[^-]*$)

Try this.Replace by X.See demo.

https://regex101.com/r/bW3aR1/18

For java it will be

[^-\\n](?=.*-[^-]*$)

The lookahead condition will select only those which are to be replaced by X.

Upvotes: 1

Related Questions