Scala 根据用户输入的名字随机推荐用户名
不是copy就能用的,要理解逻辑
逻辑
- 根据用户名字判断,
如果名字长度是0,或者纯数字的名字,或者包含手机号,或者名字太长,则使用词组(写死的),来作为组装前的 ==“原型” ==。
否则使用用户名自己的名字作为原型进行拼接推荐 - 如果长度小于6,先用字母补齐至6,再用10位数的数字做一个随机长度的数字(避免了数字长度大于10,导致可能出现手机号)
- 如果长度大于等于6,则随机用字母+数字进行拼接。
前提:(可自己设置好)
传进来的名字是合法的
假设用户名长度是6个字节-16个字节
注意
StringUtil.getCharLength(name),这个是查字符串的字节数的
isLocalExistName(recommendName),这个是查询数据库里是否有该名字的方法
scala版本
@RequestMapping(value = Array("/recommendUserName"), method = Array(RequestMethod.POST))@ResponseBodydef recommendUserName(req: HttpServletRequest,response: HttpServletResponse,@RequestParam(defaultValue = "", required = false, value = "userName") userName: String,@RequestParam(defaultValue = "", required = false, value = "mobile") mobile: String): JsonResult = {....val recommendName = userNameRecommendService.getRecommendUserName(userName)....
}
def getRecommendUserName(userName: String): JavaList[String] &#61; {val name &#61; getInitialName(userName) var recommendName:String &#61; ""val nameLen &#61; StringUtil.getCharLength(name)if(nameLen<6){do{recommendName&#61;name&#43;getRandomStrABC(6-nameLen)recommendName&#61;recommendName&#43;getRandomStrNumber(10)}while(!isLocalExistName(recommendName)) }else{do{val a&#61;new Random().nextInt(16-nameLen)val b&#61;16-nameLen-arecommendName&#61;name&#43;getRandomStrABC(a)&#43;getRandomStrNumber(b)}while(!isLocalExistName(recommendName)) }
}
当小于6的时候的效果
当大于6的时候的效果
private def getRandomStrABC(count: Int): String &#61; {var str &#61; ""for (i <- 1 to count) {val c &#61; &#39;a&#39; &#43; (new Random()).nextInt(26)str &#61; str &#43; c.toChar}str}
private def getRandomStrNumber(count: Int): String &#61; {var str &#61; ""val c &#61;new Random().nextInt(count)for(i<-1 to c){val x &#61; (new Random()).nextInt(10)str &#61; str &#43; x}str}
val namePreSet&#61;Array("童姥","拖把","王子","旺财","旺仔","蚊子","乌龟","乌鸦","西瓜","咸菜","象牙","小白","小呆","小狗","小乖","小米","小七","小强","小熊","小猪","猩猩","熊猫","雪糕","雪郎","秧李","野兔","淫魔","油头","仔仔","战童","猪头","竹竿","竹子","叶子","糖糖","小蜜蜂","小燕子","小屁孩","大嘴","大虫","石头","稻草人","拼命郎")def getInitialName(userName:String): String &#61;{val length &#61; StringUtil.getCharLength(userName)val roleId&#61;math.abs((new Random()).nextInt % (namePreSet.length))var name &#61; ""val number &#61; userName.replaceAll("\\d&#43;","")if(number.length&#61;&#61;0||isExistPhone(userName)||length>16||length&#61;&#61;0){name &#61; namePreSet.apply(preId)}else{name&#61;userName}name}
private def isExistPhone(name:String): Boolean &#61;{val pattern &#61; new Regex("[1]([3-9])[0-9]{9}")val number&#61;(pattern findAllIn name).mkString("") val p &#61; Pattern.compile("^[1]([3-9])[0-9]{9}$")val m &#61; p.matcher(number)if(m.matches()){return true}return false}