2013-02-17 53 views
0

我正在構建SMS網關,如果SMS消息在將其持久保存到數據庫之前有任何憑據信息(例如密碼),我想要屏蔽該信息。使用正則表達式從字符串中刪除一些額外的文本

下面是代碼:

String message = "Your password is [MASK:1234]!"; 

boolean bMasked = message.matches("(\\[MASK:)*(\\])"); 
String plainText = message.replaceAll(..., ""); 
String withStars = message.replaceAll("...", "*"); 

System.out.println("bMasked: " + bMasked); 
System.out.println("plainText: " + plainText); 
System.out.println("withStars: " + withStar); 

我在正則表達式知識貧乏,所以我需要你的幫助,如果可以得到下面的輸出:

bMasked: true 
plainText: Your password is 1234! 
withStars: Your password is ****! 
+2

您確實想要存儲e與密碼中的字符一樣多嗎?這不是安全明智的。它提供了太多的提示,無論得到這些信息來破解密碼。 – m0skit0 2013-02-17 10:23:35

+0

@ m0skit0 +1你說得對,它不應該有相同的長度。 – 2013-02-17 10:24:25

+0

爲什麼在短信中包含有關密碼的行(無論如何將被屏蔽)(謝天謝地)? – kjetilh 2013-02-17 10:25:26

回答

1
String message = "Your password is [MASK:1234]!"; 

boolean bMasked = message.matches(".*\\[MASK:[^\\]]*\\].*"); 
String plainText = message.replaceAll("\\[MASK:([^\\]]*)\\]", "$1"); 
String withStars = message.replaceAll("\\[MASK:[^\\]]*\\]", "******"); 

System.out.println("bMasked: " + bMasked); 
System.out.println("plainText: " + plainText); 
System.out.println("withStars: " + withStars); 

給你:

bMasked: true 
plainText: Your password is 1234! 
withStars: Your password is ******! 
+0

+1完美。謝謝! – 2013-02-17 10:35:38

+0

嗯,'!'不是掩碼的一部分,如果我刪除它'bMasked'將會是'false'。 – 2013-02-17 10:39:27

+0

@ Eng.Fouad match的意思是「返回: 如果且僅當此字符串與給定正則表達式匹配時才爲true」!!也是您的字符串的一部分。你想要什麼? – Kent 2013-02-17 10:42:31