允许1-9和破折号正则表达式

时间:2016-06-03 04:35:25

标签: javascript regex

这将允许用户输入a-z,但如何添加0-9并短划线? /^[a-zA-Z\s]*$/;

2 个答案:

答案 0 :(得分:1)

/^[a-zA-Z\d\s-]*$/
  1. 字符类([])的短划线 不需要转义,否则请使用\-
  2. 要匹配数字,您可以使用0-9,也可以只使用\d,具体取决于您的正则表达式。
  3. 正则表达式解释:

    ^[a-zA-Z\d\s-]*$
    
    Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed) «^»
    Match a single character present in the list below «[a-zA-Z\d\s-]*»
       Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
       A character in the range between “a” and “z” (case insensitive) «a-z»
       A character in the range between “A” and “Z” (case insensitive) «A-Z»
       A “digit” (any decimal number in any Unicode script) «\d»
       A “whitespace character” (any Unicode separator, tab, line feed, carriage return, vertical tab, form feed, next line) «\s»
       The literal character “-” «-»
    Assert position at the end of a line (at the end of the string or before a line break character) (line feed) «$»
    

答案 1 :(得分:0)

您正在寻找/^[1-9-]*$/

这是一个Javascript示例:

var reg = new RegExp("^[1-9-]*$");
var s = '1234-5678';
if (reg.exec(s)) {
    console.log("Match\n");
} else {
    console.log("No match\n");
}