如何通过正则表达式验证字符串 [英] how to validate string by regular expression

查看:114
本文介绍了如何通过正则表达式验证字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想插入值如

string1.string2

string1_string2

string1 string2



我的代码是

正则表达式str = 正则表达式( @  [a-zA-Z0-9] + $); 
string string1 = hello;
string string2 = codeproject;
if (str.IsMatch(string1 + .. + string2))
{
Console.WriteLine( );
}
else
Console.WriteLine( no);



输出为是

解决方案

);
string string1 = hello;
string string2 = codeproject;
if (str.IsMatch(string1 + .. + string2))
{
Console.WriteLine( yes);
}
else
控制台。 WriteLine( no);



输出为是


您只能锚定模式的结尾。

所有这些测试都是测试字符串末尾至少有1个字母数字。

你可能想要:

 Regex str =  new 正则表达式( @  ^ [a -Za-Z0-9] + 

);



模式匹配整个字符串。



我不清楚你的意思通过:

我想插入值,如
string1.string2
string1_string2
string1 string2



与模式有什么关系?





怎么样:

 Regex str =  new 正则表达式( @  ^ [a-zA-Z0-9] + [\ ._] [a-zA-Z0-9] + 


I want to insert value like
string1.string2
string1_string2
string1 string2

my code is

 Regex str = new Regex(@"[a-zA-Z0-9]+$");
string string1="hello";
string string2="codeproject";
 if (str.IsMatch(string1+".."+string2))
            {
                Console.WriteLine("yes");
            }
            else
                Console.WriteLine("no");


output is yes

解决方案

"); string string1="hello"; string string2="codeproject"; if (str.IsMatch(string1+".."+string2)) { Console.WriteLine("yes"); } else Console.WriteLine("no");


output is yes


You only anchored the end of the pattern.
All this tests is that there is at least 1 alpha-numeric at the end of the test-string.
You probably wanted:

Regex str = new Regex(@"^[a-zA-Z0-9]+


");


to pattern match the whole string.

I'm unclear about what you mean by:

I want to insert value like 
string1.string2
string1_string2
string1 string2


What does that have to do with the pattern?

[Edit: following comment below]
How about:

Regex str = new Regex(@"^[a-zA-Z0-9]+[ \._][a-zA-Z0-9]+


这篇关于如何通过正则表达式验证字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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