admin管理员组

文章数量:1307668

I'm using this RexExp code var userIdPattern = new RegExp('^([A-z0-9_.]{4,15})$');, I want to check if last character was dot (.) then .test() returns me false:

var userIdPattern = new RegExp('^([A-z0-9_.]{4,15})$');
console.log(userIdPattern.test('Omid.my.')); // -> I need this to be false

and in this case return me true:

userIdPattern.test('Omid.my'); //-> true

I'm using this RexExp code var userIdPattern = new RegExp('^([A-z0-9_.]{4,15})$');, I want to check if last character was dot (.) then .test() returns me false:

var userIdPattern = new RegExp('^([A-z0-9_.]{4,15})$');
console.log(userIdPattern.test('Omid.my.')); // -> I need this to be false

and in this case return me true:

userIdPattern.test('Omid.my'); //-> true
Share Improve this question asked Aug 11, 2013 at 12:36 PejmanPejman 2,6465 gold badges41 silver badges67 bronze badges 4
  • /\.$/ this should do.. returns true but later you can use exclamation mark to make it false. – Mr_Green Commented Aug 11, 2013 at 12:39
  • 1 Are you sure you want to use A-z? That includes: [ ] \ ^ ` _. – 7stud Commented Aug 11, 2013 at 12:42
  • @7stud yes, user name must contains "[A-z], [0-9], _, ." but dot and underscore can not be first character and last character. – Pejman Commented Aug 11, 2013 at 12:45
  • So a valid user names is "Joe^]`Smith? It's pretty clear to me that you do not know what characters are included in the range A-z because you then repeated one of those characters by writing '_' in your character class. – 7stud Commented Aug 11, 2013 at 12:47
Add a ment  | 

2 Answers 2

Reset to default 5

Following the update, a more appropriate regex might be:

var userIdPattern = new RegExp('^([A-Za-z0-9\[\]\\^`][A-z0-9_.]{2,13}[A-Za-z0-9\[\]\\^`])$');

That is, if you want to include other special characters in the usernames like 7stud mentioned in his ment and only exclude . and _ from the first and last characters.

Otherwise, to prevent those characters, I would suggest:

var userIdPattern = new RegExp('^([A-Za-z0-9][A-Za-z0-9_.]{2,13}[A-Za-z0-9])$');

Fiddle to test.

You can make it like this

^([A-z0-9_.]{3,14}[A-z0-9])$

Edit after reading your ment

^[a-z0-9][a-z0-9_.]{2,13}[a-z0-9]$

Preview

Also I suggest you use flag the i to ignore case:

var userIdPattern = new RegExp('^[a-z0-9][a-z0-9_.]{3,13}[a-z0-9]$', 'i');

本文标签: regexjavascript regExp check last characterStack Overflow