admin管理员组

文章数量:1415673

What are the JavaScript and PHP regex patterns if a string is to fulfill the following conditions:

  1. The string should be between (and including) 4 and 20 characters
  2. It can contain only lowercase alphabets and, optionally, digits.
  3. It MUST contain at least 1 alphabet

The following strings formats are acceptable :

  • randy
  • randy39
  • 39randy
  • r789456123

The following are NOT acceptable:

  • ran
  • 3546
  • r_andy
  • __3912

What are the JavaScript and PHP regex patterns if a string is to fulfill the following conditions:

  1. The string should be between (and including) 4 and 20 characters
  2. It can contain only lowercase alphabets and, optionally, digits.
  3. It MUST contain at least 1 alphabet

The following strings formats are acceptable :

  • randy
  • randy39
  • 39randy
  • r789456123

The following are NOT acceptable:

  • ran
  • 3546
  • r_andy
  • __3912
Share Improve this question edited Sep 10, 2012 at 20:58 Wiseguy 20.9k9 gold badges67 silver badges83 bronze badges asked Jan 3, 2012 at 11:22 dinchakpianistdinchakpianist 2191 gold badge4 silver badges12 bronze badges 3
  • 5 Have you tried something to solve your task or you just came to SO for munity to do your work? – zerkms Commented Jan 3, 2012 at 11:23
  • I've tried /^([a-z0-9]){3,5}$/ – dinchakpianist Commented Jan 3, 2012 at 11:25
  • Try /^([a-z0-9]{4,20})$/ if you need the capturing brackets, or /^[a-z0-9]{4,20}$/ if you don't, but that doesn't test for at least 1 alpha – Mark Baker Commented Jan 3, 2012 at 11:30
Add a ment  | 

2 Answers 2

Reset to default 6

You could use a lookahead assertion to verify that the string contains a letter somewhere.

/^(?=.*[a-z])[a-z0-9]{4,20}$/

This should work in both JavaScript and PHP alike.

Use two regexes: /^[a-z0-9]{4,20}$/ and /[a-z]/ (the actual syntax might differ between PHP and Javascript)

本文标签: