加密内容(例如:验证码)
方法一:正则,需要匹配位数、内容
String str = "【肥猫快递】验证码123456,您的快件尾号2298正享受小鱼干服务,快递员小帅比:挨提大佬,请在送达时提供此验证码给快递小哥。" ;
Pattern pattern = Pattern. compile ( "验证码[\\d]{6}" ) ;
Pattern pattern1 = Pattern. compile ( "[\\d]{6}" ) ;
Matcher matcher = pattern. matcher ( str) ;
Matcher matcher1 = pattern1. matcher ( str) ;
String group = "" ;
if ( matcher. find ( ) ) {
group = matcher. group ( ) ;
System. out. println ( "group = " + group) ;
str = matcher. replaceAll ( "******" ) ;
}
System. out. println ( "str = " + str) ;
}
(一)
Exception in thread "main" java. lang. IllegalStateException: No match found
at java. util. regex. Matcher. group ( Matcher. java: 536 )
at java. util. regex. Matcher. group ( Matcher. java: 496 )
at com. gc. api. controller. FallbackController. main ( FallbackController. java: 49 )
方法2截取内容,不用匹配位数
String str = "【韵达快递】验证码123456789,您的快件尾号2298正享受智橙网服务,快递员小帅比:挨提大佬,请在送达时提供此验证码给快递小哥。" ;
String verifyCode = str. substring ( str. indexOf ( "验证码" ) + 3 , str. indexOf ( ",您的快件尾号" ) ) ;
String replace = str. replace ( verifyCode, "******" ) ;
System. out. println ( "replace = " + replace) ;
System. out. println ( "verifyCode = " + verifyCode) ;