简体   繁体   English

Java Regex后缀

[英]Java Regex Suffix

I am currently working with java regexes attempting to match a username with the following conditions: 我目前正在使用java regexes尝试匹配具有以下条件的用户名:

  1. Must start with letter (upper or lower case) 必须以字母开头(大写或小写)
  2. Must be no more than 8 chars in length 长度不得超过8个字符
  3. May have digits, but they must be at the end (so sjh23 would match but not sj23h) 可能有数字,但它们必须在最后(所以sjh23会匹配但不是sj23h)

I know to start with ^[A-Za-z] and the length can be managed with {0,7} but I don't know how to make it so any digits would be a suffix. 我知道从^ [A-Za-z]开始,长度可以用{0,7}来管理,但我不知道怎么做,所以任何数字都是后缀。

Thanks for any help. 谢谢你的帮助。

To check length of string with regex you can use look ahead mechanism and add (?=^.{1,8}$) at start of regex. 要使用正则表达式检查字符串的长度,您可以使用预读机制并在正则表达式的开头添加(?=^.{1,8}$)

So your regex can look like 所以你的正则表达式看起来像

(?=^.{1,8}$)[A-Za-z]+\\d*

Also you can do it with length() method like 你也可以用length()方法来做

if(yourString.matches("[A-Za-z]+\\d*")  &&  yourString.length()<=8){//...
//you dont need to check if yourString.length()>=1 since [A-Za-z]+ makes string
//to contain at least one character

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM