过滤字符串 [英] Filter a String

查看:93
本文介绍了过滤字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保字符串中只有此范围内的字符

I want to make sure a string has only characters in this range

[a-z]&& [A-Z]&& [0-9]&& [-]

[a-z] && [A-Z] && [0-9] && [-]

所有字母和数字加上连字符。
我尝试过此操作...

so all letters and numbers plus the hyphen. I tried this...

C#应用程序:

        char[] filteredChars = { ',', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '{', '}', '[', ']', ':', ';', '"', '\'', '?', '/', '.', '<', '>', '\\', '|' };
        string s = str.TrimStart(filteredChars);

此TrimStart()似乎只适用于没有象$%等字符的字母

This TrimStart() only seems to work with letters no otehr characters like $ % etc

我执行错了吗?
还有更好的方法吗?

Did I implement it wrong? Is there a better way to do it?

我只是想避免循环访问每个字符串的索引检查,因为将有很多字符串要做...

I just want to avoid looping through each string's index checking because there will be a lot of strings to do...

有什么想法?

谢谢!

推荐答案

这似乎是使用正则表达式

bool stringIsValid = Regex.IsMatch(inputString, @"^[a-zA-Z0-9\-]*?$");

针对miguel的评论,您可以执行以下操作删除所有不需要的字符:

In response to miguel's comment, you could do this to remove all unwanted characters:

string cleanString = Regex.Replace(inputString, @"[^a-zA-Z0-9\-]", "");

请注意,插入符号( ^ )是现在将放在字符类中,从而将其取反(匹配任何不允许的字符)。

Note that the caret (^) is now placed inside the character class, thus negating it (matching any non-allowed character).

这篇关于过滤字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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