Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 允许1-9和破折号正则表达式_Javascript_Regex - Fatal编程技术网

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

Javascript 允许1-9和破折号正则表达式,javascript,regex,Javascript,Regex,这将允许用户输入a-z,但如何添加0-9和破折号/^[a-zA-Z\s]*$/ /^[a-zA-Z\d\s-]*$/ 字符类([])末尾的破折号不需要转义,否则使用\- 要匹配数字,您可以使用0-9或简单地使用\d,具体取决于您的正则表达式风格 正则表达式解释: ^[a-zA-Z\d\s-]*$ Assert position at the beginning of a line (at beginning of the string or after a line break chara

这将允许用户输入a-z,但如何添加0-9和破折号<代码>/^[a-zA-Z\s]*$/

/^[a-zA-Z\d\s-]*$/
  • 字符类(
    []
    )末尾的破折号不需要转义,否则使用
    \-
  • 要匹配数字,您可以使用
    0-9
    或简单地使用
    \d
    ,具体取决于您的正则表达式风格

  • 正则表达式解释:

    ^[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-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");
    }
    

    是否允许用户输入[空白]?是否阅读了有关如何使用正则表达式的教程?因为这是非常普遍的和基本的。你是说涵盖0-9还是1-9,问题的标题和上下文各不相同。@SpencerWieczorek我只是不知道把
    -
    \s
    放在哪里是为了什么?我可以执行
    \s@
    ?@HarisZ是一个空格字符。如果您出于某种原因希望匹配
    “[空白字符]@”
    \s
    可以匹配“空白字符”(任何Unicode分隔符、制表符、换行符、回车符、垂直制表符、换行符、下一行),我可以将
    -
    放在
    后面的第一个字符中吗[
    ?什么是
    =~
    ?我第一次在Perl中看到这一点时,它正在测试变量
    $s
    中的值是否与正则表达式匹配。我不确定为什么会给出Perl中的示例,JavaScript示例更合适。@Spencer Wieczorek-很好的一点…我有点不考虑。谢谢!