正则表达式只允许 1 个字符 [英] Regex allows only 1 character

查看:58
本文介绍了正则表达式只允许 1 个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$rex = '/^[^<,"@?=>|;#]$/i';

这个正则表达式有问题.这个想法是检查输入字段中的某些字符,如果存在,则抛出错误.

I'm having trouble with this regular expression. The idea is that the input fields are checked for certain characters and if present, throw an error.

这个正则表达式会为每个长度超过 1 个字符的字符串抛出错误.谁能告诉我我做错了什么?

This regex is throwing errors for every string longer than 1 character. Can anyone tell me what I'm doing wrong?

人们说他们看不到我想用这个正则表达式做什么.如果以下字符之一是输入字符串的一部分,我想要做的是拒绝输入:

People are saying they don't see what I want to do with this regex. What I want to do is refuse the input if one of the following characters is part of the entered string:

<> , " @ ? = | ; #

< > , " @ ? = | ; #

JG 的有效"正则表达式可以解决问题.

JG's "valid" regex does the trick.

推荐答案

你在表达式后面有 $ ,在开头有 ^ ,这意味着你正在接受正好一个字符.

You have the $ after your expression and the ^ in the beginning, which means you are accepting exactly one character.

编辑(基于评论):

您可以尝试查看您的输入字段是否具有有效字符,通过将其与此匹配(如果匹配,则表示没有无效字符):

You can try to see if your input fields only have valid characters, by matching it against this (if it matches, it means there are no invalid characters):

$rex = '/^[^<,"@$?=>|;#]+$/i'

你也可以反过来,即测试你的输入字段是否有任何无效字符,使用chaos提供的正则表达式:

You can also do the reverse, that is, test if your input fields have any invalid characters, using the regex provided by chaos:

$rex = '/[<,"@$?=>|;#]/';

这样,如果正则表达式匹配,则意味着您有无效字符.

This way, if the regex matches, then it means you have invalid characters.

这篇关于正则表达式只允许 1 个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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