admin管理员组

文章数量:1291455

How can I write a regular expression in javascript that only allows users to write this:

abc.def, abc-def or abc

So basically match a pattern that only contains letters (only lowercase [a-z]) and a . or -. But does not match - or . at the beginning or end of string or multiple times(only one . or - per string)

So not allowing them to do:

..... abc...abc abc.abc.... abc----.... ...abc.abc .abc -abc etc.

How can I write a regular expression in javascript that only allows users to write this:

abc.def, abc-def or abc

So basically match a pattern that only contains letters (only lowercase [a-z]) and a . or -. But does not match - or . at the beginning or end of string or multiple times(only one . or - per string)

So not allowing them to do:

..... abc...abc abc.abc.... abc----.... ...abc.abc .abc -abc etc.

Share Improve this question edited Jun 24, 2012 at 23:23 georgesamper asked Jun 24, 2012 at 22:51 georgesampergeorgesamper 5,1795 gold badges44 silver badges59 bronze badges 3
  • Are dot or hyphen allowed as the first character of the string? – John Watts Commented Jun 24, 2012 at 23:08
  • I forgot to add that. No, a dot or hyphen is not allowed at the beginning of the string. – georgesamper Commented Jun 24, 2012 at 23:13
  • May be this - /^[a-z]+(?:[-.]?[a-z]+)?$/ - is what you're looking for? ) Single dash or dot in ALL the string. – raina77ow Commented Jun 24, 2012 at 23:18
Add a ment  | 

1 Answer 1

Reset to default 10

Regex would be: /^[a-z]+([\.\-]?[a-z]+)?$/

JavaScript:

var text = 'abc.def';
var pattern = /^[a-z]+([\.\-]?[a-z]+)?$/;
if (text.match(pattern)) {
  print("YES!");
} else {
  print("NO!");
}

See and test the code here.

本文标签: javascriptRegEx only one dot inside string not at beginning or endStack Overflow