字符串的正则表达式不以特殊的字符和空格开头 [英] Regular expression for string not start with special caracter and space
问题描述
我必须制作正则表达式,不允许字符串以sprecial caracter开头。
例如:
45@gf.com - 正确
@ 45gm.com - 错误
我该怎么做?
什么我试过了:
i让这个正则表达式...
string TrNo = txtConsignor.Text.ToString() ;
TrNo = System.Text.RegularExpressions.Regex.Replace(TrNo,[^ a-zA-Z0-9 \\ t],);
txtConsignor.Text = TrNo.TrimStart();
i have to make regular expression which not allow string start with sprecial caracter.
for exampel :
45@gf.com - right
@45gm.com - wrong
how can i do this ?
What I have tried:
i have make this regular expression...
string TrNo = txtConsignor.Text.ToString();
TrNo = System.Text.RegularExpressions.Regex.Replace(TrNo, "[^a-zA-Z0-9\\s]", "");
txtConsignor.Text = TrNo.TrimStart();
推荐答案
你在做什么并不禁止特殊字符,它会删除它们。并且它也不要求它们在开始时!
因此,如果你的字符串是@ 45gm.com,那么它将它转换为45gmcom 而不是告诉任何人它已经完成了它。 因此,存储(或以其他方式处理)的内容也不是有效的电子邮件,并且在解决问题时为时已晚。更糟糕的是,它对你的正确字符串做了同样的事情:45@gf.com成为45gfcom
你需要的是用它作为一个正则表达式并检查结果:
What you are doing doesn't prohibit special characters, it removes them. And it doesn't require them to be at the start, either!
So if your string is "@45gm.com" then it converts it to 45gmcom and doesn't tell anyone it's done it. So what gets stored (or otherwise processed) isn;t a valid email either, and gives problems way on down the line, when it's too late to fix it. Worse, it does the same thing with your "correct" string: "45@gf.com" becomes "45gfcom"
What you need is to use it as a regex and check the result:
Match m = Regex.Match(trNo, "^[^a-zA-Z0-9\\s]");
if (m.Success)
{
... report problem to user ...
return;
}
这篇关于字符串的正则表达式不以特殊的字符和空格开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!