RegEx only one dot inside string not at beginning or end

帅比萌擦擦* 提交于 2021-02-16 19:43:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!