检查字符串无效字符?最聪明的办法吗? [英] Check string for invalid characters? Smartest way?

查看:111
本文介绍了检查字符串无效字符?最聪明的办法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查一些字符串无效字符。随着无效字符,我的意思是不应该存在的字符。什么字符是这些?这是不同的,但我认为那不是说importan,重要的是我应该怎么做的,什么是最简单,最好的方式(性能)来做到这一点?

I would like to check some string for invalid characters. With invalid characters I mean characters that should not be there. What characters are these? This is different, but I think thats not that importan, important is how should I do that and what is the easiest and best way (performance) to do that?

让说,我只想字符串,其中包含的'A-Z','空','','$','0-9'

Let say I just want strings that contains 'A-Z', 'empty', '.', '$', '0-9'

所以,如果我有这样一个字符串 HELLO计算器=>无效,因为的'一',。 好了现在该怎么办呢?我可以做一个名单,其中,焦炭> ,放在它的每一个字符是不允许的,并检查字符串列表。也许不是一个好主意,因为有很多字符的话。但我可以做一个包含所有允许的字符的右侧列表?接着?对于字符串中的每个字符我比较名单,其中,焦炭> ?任何智能code这个?而另一个问题:如果我想补充AZ到名单,其中,焦炭> 我必须手动添加25个字符,但这些字符是因为我在ASCII表知道65-90 ,我可以添加它们更容易?有什么建议么?谢谢

So if i have a string like "HELLO STaCKOVERFLOW" => invalid, because of the 'a'. Ok now how to do that? I could make a List<char> and put every char in it that is not allowed and check the string with this list. Maybe not a good idea, because there a lot of chars then. But I could make a list that contains all of the allowed chars right? And then? For every char in the string I have to compare the List<char>? Any smart code for this? And another question: if I would add A-Z to the List<char> I have to add 25 chars manually, but these chars are as I know 65-90 in the ASCII Table, can I add them easier? Any suggestions? Thank you

推荐答案

您可以使用常规的前pression此:

You can use a regular expression for this:

Regex r = new Regex("[^A-Z0-9.$ ]$");
if (r.IsMatch(SomeString)) {
    // validation failed
}


AZ创建人物列表 0-9 你可以使用一个简单的循环:


To create a list of characters from A-Z or 0-9 you would use a simple loop:

for (char c = 'A'; c <= 'Z'; c++) {
    // c or c.ToString() depending on what you need
}

但你并不需要一个与正则表达式 - pretty的每得多正则表达式引擎理解的范围语法( AZ

这篇关于检查字符串无效字符?最聪明的办法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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