开发者

alphanumeric with at least 1 character

Ok so I finally figured out that I need the following:

So the regular expression has to perform:

  1. alphanum开发者_StackOverflow中文版eric
  2. at least 1 letter
  3. must have between 4 and 8 characters (either a letter/digit).

i.e. an alphanumeric string, that must have at least 1 letter, and be between 4-8 in length. (so it can't be just all numbers or just all letters).

can all of this be done in a single regex?


I'm assuming you mean alphaunumeric, at least one letter, and 4 to 8 characters long.

Try this:

(?=.*[a-zA-Z])[a-zA-Z0-9]{4,8}
  • (?= - we're using a lookahead, so we can check for something without affecting the rest of the match

  • .*[a-zA-Z] - match for anything followed by a letter, i.e. check we have at least one letter

  • [a-zA-Z0-9]{4,8} - This will match a letter or a number 4 to 8 times.

However, you say the intention is for "it can't be just all numbers or just all letters", but requirements 1, 2 and 3 don't accomplish this since it's can be all letters and meet all three requirements. It's possible you want this, with an extra lookahead to confirm there's at least one digit:

(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{4,8}

The use of a-zA-Z isn't very international friendly, so you may be better off using an escape code for "letter" if available in your flavour of Regular Expressions.

Also, I hope this isn't matching for acceptable passwords, as 4 characters probably isn't long enough.


number 2 and 3 seem to contradict. The following will match alphanumeric between 4 and 8:

/[0-9a-zA-Z]{4,8}/


?Regex.IsMatch("sdf", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
false
?Regex.IsMatch("sdfd", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
true
?Regex.IsMatch("1234", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
false

Warning on **.* and .+:

// At least one letter does not match with .*
?Regex.IsMatch("1111", "(?=.*[a-zA-Z])[a-zA-Z0-9]{4,8}")
false

?Regex.IsMatch("1aaa", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
true


[a-zA-Z0-9]{4,8}

The first part specifies alphanumeric, and the 2nd part specifies from 4 to 8 characters.


Try: [a-zA-Z0-9]{4,8}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜