Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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
Regex 是否从正则表达式字符类中排除连字符?_Regex - Fatal编程技术网

Regex 是否从正则表达式字符类中排除连字符?

Regex 是否从正则表达式字符类中排除连字符?,regex,Regex,为了说明这个微妙的问题,以下是一些JavaScript示例,您可以在浏览器中进行测试: /[2-5]+/.test('2') // true, as expected. /[2-5]+/.test('-') // false, as expected. /[2-5]+/.test('2-') // true. WTF?!!! 问题: 这是一个bug还是一个特性 测试字符类时如何排除连字符 更新 这是一个愚蠢的问题。我的错。在再次编码之前需要休息一下 试试这样的东西 /^[2-5]+$

为了说明这个微妙的问题,以下是一些JavaScript示例,您可以在浏览器中进行测试:

/[2-5]+/.test('2')   // true, as expected.
/[2-5]+/.test('-')   // false, as expected.
/[2-5]+/.test('2-')  // true. WTF?!!!
问题:

  • 这是一个bug还是一个特性
  • 测试字符类时如何排除连字符 更新
    这是一个愚蠢的问题。我的错。在再次编码之前需要休息一下

    试试这样的东西

    /^[2-5]+$/.test('2-')
    

    这将确保从字符串的前面(^)到末尾($)只有数字2-5。

    感谢您的理解!:)我能在5分钟内接受你的回答!