需要一个正则表达式来检查字符串是否仅包含字母a-z和数字以及下划线(_)和连字符(-) [英] Need a regex that will check if the string only consist letters a-z and numbers and underscore(_) and hyphen(-)

查看:672
本文介绍了需要一个正则表达式来检查字符串是否仅包含字母a-z和数字以及下划线(_)和连字符(-)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个正则表达式,它将检查字符串是否仅由字母a-z,数字,下划线(_)和连字符(-)组成.我已经尝试过了,但是不起作用:

I'm looking for a regex that will check if the string only consists of the letters a-z, numbers, underscore (_) and hyphen (-). I have tried this, but it does not work:

if (!preg_match('/^a-zA-Z0-9_-$/', $string)) {
  $reg_Error[] = 2;
}

还可以使用正则表达式检查长度吗?如果没有,我将使用PHP来完成.

Also, can I check the length with regex? If not, I will just do it with PHP.

推荐答案

您必须将正则表达式/^a-zA-Z0-9_-$/放在字符类/[...]/中.
这意味着您可以在字符类中匹配任何个字符.您还应该指定一个量词,因为/^[a-zA-Z0-9_-]$/仅匹配一个字符.

You have to put your regex /^a-zA-Z0-9_-$/ in a character class /[...]/.
It means you can match any character in the character class. You should also specify a quantifier, because /^[a-zA-Z0-9_-]$/ will match only one character.

示例:
/^[a-zA-Z0-9_-]+$/带有+符号的符号,您将其匹配了一次或多次
/^[a-zA-Z0-9_-]{1,}$/与上述相同
/^[a-zA-Z0-9_-]{10,20}$/长度在10到20个字符之间.
/^[a-zA-Z0-9_-]{15}$/它必须完全是 15个字符.您可以使用它来检查字符串长度.

Examples:
/^[a-zA-Z0-9_-]+$/ with the + sign you match it one or more time
/^[a-zA-Z0-9_-]{1,}$/ the same as above
/^[a-zA-Z0-9_-]{10,20}$/ between 10 and 20 character long.
/^[a-zA-Z0-9_-]{15}$/ it has to be exactly 15 characters long. You can use it to check the string length.

您还可以使用以下关键字使您的正则表达式易于阅读:
/^[\w-]+$/与一个字符(包括下划线,字母和数字)或破折号,一次或多次匹配.

You can also use the following keyword to make your regex easy to read:
/^[\w-]+$/ which matches a word character (including underscore, letters and digits) or a dash, one or more time.

这篇关于需要一个正则表达式来检查字符串是否仅包含字母a-z和数字以及下划线(_)和连字符(-)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆