如何编写正则表达式只允许数字和“(”,“)”,“

编程入门 行业动态 更新时间:2024-10-24 20:19:27
如何编写正则表达式只允许数字和“(”,“)”,“ - ”(How to write a regex only allow numbers and “(”, “)”, “-”)

下面是我的正则表达式,但它似乎无法正常工作

/[0-9\-\(\)]/.test(str)

当我测试

/[0-9\-\(\)]/.test('(12321)213213d')

它会返回true

Below is my regex but it seems not working

/[0-9\-\(\)]/.test(str)

when I test

/[0-9\-\(\)]/.test('(12321)213213d')

It will return true

最满意答案

你实际测试的是你的测试字符串中是否这些字符。 您想检查它是否只包含那些字符。 要做到这一点,你需要说从开始^到完成$它只包含那些字符。

例如

/^[0-9()-]+$/.test('(12321)213213d')

What you're actually testing is if any of those characters are in your test string. You want to check if it contains only those characters. To do that, you need to say from start ^ to finish $ it only contains those chars.

e.g.

/^[0-9()-]+$/.test('(12321)213213d')

更多推荐

本文发布于:2023-08-07 19:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465615.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:只允许   数字   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!