mstabosz Posted September 29, 2013 Share Posted September 29, 2013 I thought this would be straightforward, but I'm missing something. Here are the rules: 3 to 20 characters. Letters either upper or lower case are allowed. Numbers are allowed. Nothing else is allowed. So jsmith is okay, as is jsmith123, but jsmith! is FORBIDDEN. So using what I know about regular expressions and a regular expressions tester at http://regexpal.com/, I came up with this: [a-zA-Z0-9]{3,20} That allows jsmith and jsmith123, which is good, but it also allows jsmith!, which is bad. The regex tester highlights the allowed characters in all instances and leaves the exclamation point alone. But what I want is an all or nothing thing. If that ! gets in there, throw away the rest of the expression. I have a feeling I'm misunderstanding something about regular expressions. Link to comment https://forums.phpfreaks.com/topic/282515-trying-to-construct-a-regular-expression-that-only-accepts-input-with-letters-and-numbers/ Share on other sites More sharing options...
requinix Posted September 29, 2013 Share Posted September 29, 2013 It's less "all or nothing" but instead "everything in the string from the beginning to the end". ^[a-zA-Z0-9]{3,20}$^ and $ meaning beginning- and end-of string respectively. Link to comment https://forums.phpfreaks.com/topic/282515-trying-to-construct-a-regular-expression-that-only-accepts-input-with-letters-and-numbers/#findComment-1451627 Share on other sites More sharing options...
Irate Posted September 29, 2013 Share Posted September 29, 2013 Use the negative lookahead flag. ([a-zA-Z0-9+]{3,20}(?![^a-zA-Z0-9])) Should do the trick. Edit: I brushed up the regex a bit... and it didn't work out as I planned it to do. I'll think of something else. Link to comment https://forums.phpfreaks.com/topic/282515-trying-to-construct-a-regular-expression-that-only-accepts-input-with-letters-and-numbers/#findComment-1451630 Share on other sites More sharing options...
mstabosz Posted September 29, 2013 Author Share Posted September 29, 2013 Thanks requinix. That worked out great! Thanks to you too Irate. Although I didn't try your solution, I appreciate the help. Link to comment https://forums.phpfreaks.com/topic/282515-trying-to-construct-a-regular-expression-that-only-accepts-input-with-letters-and-numbers/#findComment-1451674 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.