开发者

Need help with a regular expression in Javascript

The box should allow:

  • U开发者_运维知识库ppercase and lowercase letters (case insensitive)
  • The digits 0 through 9
  • The characters, ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • The character "." provided that it is not the first or last character


Try

^(?!\.)(?!.*\.$)[\w.!#$%&'*+\/=?^`{|}~-]*$

Explanation:

^         # Anchor the match at the start of the string
(?!\.)    # Assert that the first characters isn't a dot
(?!.*\.$) # Assert that the last characters isn't a dot
[\w.!#$%&'*+\/=?^`{|}~-]*   # Match any number of allowed characters
$         # Anchor the match at the end of the string


Try something like this:

// the '.' is not included in this:
var temp = "\\w,!#$%&'*+/=?^`{|}~-";

var regex = new RegExp("^["+ temp + "]([." + temp + "]*[" + temp + "])?$");
//                                      ^
//                                      |
//                                      +---- the '.' included here

Looking at your comments it's clear you don't know exactly what a character class does. You don't need to separate the characters with comma's. The character class:

[0-9,a-z]

matches a single (ascii) -digit or lower case letter OR a comma. Note that \w is a "short hand class" that equals [a-zA-Z0-9_]

More information on character classes can be found here:

http://www.regular-expressions.info/charclass.html


You can do something like:

^[a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~][a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~.]*[a-zA-Z0-9,!#$%&'*+-/=?^_`{|}~]$


Here's how I would do it:

/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*$/

The first part is required to match at least one non-dot character, but everything else is optional, allowing it to match a string with only one (non-dot) character. Whenever a dot is encountered, at least one non-dot character must follow, so it won't match a string that begins or ends with a dot.

It also won't match a string with two or more consecutive dots in it. You didn't specify that, but it's usually one of the requirements when people ask for patterns like this. If you want to permit consecutive dots, just change the \. to \.+.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜