简体   繁体   English

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

[英]Java Regex to mask alphanumeric string and show last 4 digits

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.我到处寻找使用正则表达式来掩盖它的Java代码示例。 I've found this post on stack but that assumes that the input is purely a number.我在堆栈上找到了这篇文章,但假设输入纯粹是一个数字。

I adjusted the regex to /\\w(?=\\w{4})/g to include characters as well.我将正则表达式调整为/\\w(?=\\w{4})/g以包含字符。 It seems to work here .它似乎在这里工作。 But when I try to implement it in java it doesn't work.但是当我尝试在 java 中实现它时,它不起作用。 Here's the line in my java code:这是我的java代码中的一行:

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

The mask ends up being the same as the accountNumber.掩码最终与 accountNumber 相同。 So obviously the regex is not working.所以显然正则表达式不起作用。 Any thoughts?有什么想法吗?

You're using replace , which doesn't use regular expressions.您正在使用replace ,它不使用正则表达式。

Try replaceAll .尝试replaceAll

使用过的replaceAll替换

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java正则表达式匹配字母数字字符串 - java regex match for alphanumeric string 如何在Java中使用正则表达式解析字符串的最后6位数字? - How do I parse the last 6 digits of a string using regex in Java? 正则表达式屏蔽除特定长度的最后两位之外的所有数字 - Regex to Mask all but Last Two Digits of a Number of Specific Length Java:如何向字母数字字符串中的数字添加整数并返回输出 - Java : How to add an int to digits in an alphanumeric string and return the output 正则表达式在Java中屏蔽除前两位数字之外的字符 - Regex to mask characters except first two digits in Java 如何使用java replaceAll(regex,replacement)方法屏蔽字符串中的最后一个括号? - How to mask last parentheses brackets in string using java replaceAll(regex, replacement) method? Java +正则表达式如何检查这样的字符串“ LOAD_filesourceB-01012008_000058.dat”的类型和数字(后6位) - Java + regex how to check such a string “LOAD_filesourceB-01012008_000058.dat” for type and number(last 6 digits) 如何在Java中使用正则表达式查找字符串的最后六位数字? - how do i find the last six digits of a string using regex in java? 在Java中使用Regex屏蔽字符串中的替代字符 - Mask Alternative chars in a String using Regex in java Java中的正则表达式,用于字母数字 - Regex in java for alphanumeric
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM