字母、数字和 - _ 的正则表达式 [英] Regular expression for letters, numbers and - _

查看:110
本文介绍了字母、数字和 - _ 的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果值是以下任何组合,我在检查 PHP 时遇到问题

I'm having trouble checking in PHP if a value is is any of the following combinations

  • 字母(大写或小写)
  • 数字 (0-9)
  • 下划线 (_)
  • 破折号 (-)
  • 点 (.)
  • 没有空格!或其他字符

几个例子:

  • 好的:screen123.css"
  • 好的:screen-new-file.css"
  • 好的:screen_new.js"
  • 不行:筛选新文件.css"

我想我需要一个正则表达式,因为当给定字符串中包含除上述字符之外的其他字符时,我需要抛出错误.

I guess I need a regex for this, since I need to throw an error when a give string has other characters in it than the ones mentioned above.

推荐答案

你想要的模式类似于 (在 rubular.com 上查看):

The pattern you want is something like (see it on rubular.com):

^[a-zA-Z0-9_.-]*$

说明:

  • ^ 是行锚点的开头
  • $ 是行尾锚点
  • [...] 是一个字符类定义
  • * 是零次或多次"重复
  • ^ is the beginning of the line anchor
  • $ is the end of the line anchor
  • [...] is a character class definition
  • * is "zero-or-more" repetition

注意文字破折号 - 是字符类定义中的最后一个字符,否则它具有不同的含义(即范围).. 在字符类定义之外也有不同的含义,但在内部,它只是一个文字 .

Note that the literal dash - is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The . also has a different meaning outside character class definitions, but inside, it's just a literal .

以下是展示如何使用此模式的片段:

Here's a snippet to show how you can use this pattern:

<?php

$arr = array(
  'screen123.css',
  'screen-new-file.css',
  'screen_new.js',
  'screen new file.css'
);

foreach ($arr as $s) {
  if (preg_match('/^[\w.-]*$/', $s)) {
    print "$s is a match\n";
  } else {
    print "$s is NO match!!!\n";
  };
}

?>

以上打印(在 ideone.com 上看到):

screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!

注意模式略有不同,使用 \w 代替.这是单词字符"的字符类.

Note that the pattern is slightly different, using \w instead. This is the character class for "word character".

这似乎符合您的规范,但请注意,这将匹配 ..... 等内容,这可能是您想要的,也可能不是.如果你能更具体地说明你想匹配什么模式,正则表达式会稍微复杂一些.

This seems to follow your specification, but note that this will match things like ....., etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.

上面的正则表达式也匹配空字符串.如果您需要至少一个字符,请使用 +(一个或多个)而不是 *(零个或多个)进行重复.

The above regex also matches the empty string. If you need at least one character, then use + (one-or-more) instead of * (zero-or-more) for repetition.

在任何情况下,您都可以进一步阐明您的规范(在提出正则表达式问题时总是有帮助的),但希望您也可以根据上述信息学习如何自己编写模式.

In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.

这篇关于字母、数字和 - _ 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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