Java Regex用于屏蔽字母数字字符串并显示最后4位数字

时间:2021-05-07 19:29:37

I have an input string that looks like any of the following:

我有一个输入字符串,看起来像以下任何一个:

  • Z43524429
  • Z43524429
  • 46D92S429
  • 46D92S429
  • 3488DFJ33
  • 3488DFJ33

Basically the string can contain alphabet characters or digits. However it cannot contain symbols, just letters and numbers. I would like to mask it so that it looks like this:

基本上字符串可以包含字母字符或数字。但它不能包含符号,只包含字母和数字。我想掩盖它,使它看起来像这样:

  • *****4429
  • ***** 4429
  • *****S429
  • ***** S429
  • *****FJ33
  • ***** FJ33

I've looked everywhere to find an java code example that uses regex to mask this. I've found this post on stack but that assumes that the input is purely a number.

我到处寻找一个使用正则表达式来掩盖它的java代码示例。我在堆栈上发现了这个帖子但是假设输入纯粹是一个数字。

I adjusted the regex to /\w(?=\w{4})/g to include characters as well. It seems to work here. But when I try to implement it in java it doesn't work. Here's the line in my java code:

我将正则表达式调整为/ \ w(?= \ w {4})/ g以包含字符。它似乎在这里工作。但是当我尝试在java中实现它时它不起作用。这是我的java代码中的行:

String mask = accountNumber.replace("\\w(?=\\w{4})", "*");

The mask ends up being the same as the accountNumber. So obviously the regex is not working. Any thoughts?

掩码最终与accountNumber相同。显然正则表达式不起作用。有什么想法吗?

1 个解决方案

#1


5  

You're using replace, which doesn't use regular expressions.

你正在使用replace,它不使用正则表达式。

Try replaceAll.

尝试replaceAll。

#1


5  

You're using replace, which doesn't use regular expressions.

你正在使用replace,它不使用正则表达式。

Try replaceAll.

尝试replaceAll。