使用正则表达式验证逗号分隔列表 [英] validate comma separated list using regex

查看:61
本文介绍了使用正则表达式验证逗号分隔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证用户是否仅使用正则表达式输入了逗号分隔的单词列表,这是否有效/是否有更好的方法:

I want to validate that the user has entered a comma separated list of words only using regex, will this work/is there a better way:

 $match = "#^([^0-9 A-z])(,\s|$))+$#";

这不是为了解析,因为我将使用explode来解析,它只是为了验证用户是否正确理解值应该用逗号分隔.

This is not for parsing, as I will use explode for that, it is merely to validate that the user has correctly understood that values should be separated with commas.

推荐答案

我不知道单独的值应该是什么样子,但也许这可以帮助您:

I don't know what the separate values should look like, but perhaps this is something that can help you:

$value = '[0-9 A-Z]+';
$match = "~^$value(,$value)*$~i";

当您知道您的值应该是什么样子时,您可以更改 $value.

When you know what your values should look like you can change $value.

从问题中提取此评论

我试图禁止 0-9 但允许 a-Z,因为,正如我所说,它应该只是一个单词列表,没有空格,只是一个单词列表.

I was trying to disallow 0-9 but allow a-Z, because, as I said it should be a list of words only, no spaces, just a list of single words.

只需更改$value

$value = '[A-Z]+';

请注意,我在 $match 中使用了 i-修饰符,它也将包含所有小写字母.

Note, that I use the i-modifier in $match, that will include all lowercase letters too.

然而,真实"csv 允许的内容不止于此,例如,您可以在每个值周围加上引号.我建议您解析该行,然后测试每个值

However, "real" csv allows a little bit more than this, for example you can put quotes around every value. I would recommend that you parse the line and then test every single value

$values = str_getcsv($line);
$valid = true;
foreach ($values as $value) {
  $valid = $valid && isValid($value);
}

str_getcsv()

这篇关于使用正则表达式验证逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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