正则表达式匹配但不应该 [英] Regex matches but shouldn't

查看:20
本文介绍了正则表达式匹配但不应该的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,用于检查是否只填写了字母数字字符,但是当我输入类似 adasd@#$ 之类的内容时,它仍然匹配,我不知道为什么.知道如何解决这个问题吗?

This is my code that checks if there are only alphanumeric characters filled in, but when i enter something like adasd@#$ it still matches and i have no idea why. Any idea how to fix this?

Match Match = Regex.Match(value.ToString(), "[0-9a-zA-Z]");
                if (Match.Success)
                {
                    return true;
                }
                else
                {
                    return false;
                }   

推荐答案

你所拥有的匹配任何包含一个字母或数字的字符串.

What you have matches any string that contains one letter or number somewhere in it.

您需要在字符串的开头和结尾添加锚点(^$),以及一个 + 以允许对于多个字符:

You need to add anchors to the beginning and end of the string (^ and $), as well as a + to allow for more than one character:

"^[0-9a-zA-Z]+$"

这意味着整个字符串必须由字母和数字组成".

This means "the entire string must be made of letters and numbers".

+ 还要求字符串中至少有一个字符.这可能是一件好事,但如果你想匹配空字符串,你也可以将其更改为 *.

The + also requires that there is at least one character in the string. This is probably a good thing, but if you want to match empty strings, as well, you can change it to *.

这篇关于正则表达式匹配但不应该的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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