问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/11181829/regex-only-one-dot-inside-string-not-at-beginning-or-end