string str = this.TextBox2.Text.Trim(); System.Text.RegularExpressions.Regex strRegex = new Regex(@"[0-9]",RegexOptions.IgnoreCase); if(strRegex.Matches(str).Count == str.Length) { Response.Write("<br>输入的全是数"); Response.Write(" "+str); } else { string pat = @"([0-9]+)"; Regex r = new Regex(pat, RegexOptions.IgnoreCase); Match m = r.Match(str); if (m.Success) { Group g = m.Groups[1]; CaptureCollection cc = g.Captures; Capture c = cc[0]; if (c.Index == 0) { Response.Write("<br>输入的不全是数,前面的数字:"); Response.Write(" "+c); } } }我也菜鸟一个.这个应该可以的,
to masong-1978,你不是说字符串首尾都不能为"-"吗单个 "-" 自然算是在首不匹配的测试例子using System; using System.Text.RegularExpressions; public class test { static void Main() { string p = @"^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])$"; string [] s = {"-", "abcd", "a-c", "-a"}; foreach(string c in s) { Console.WriteLine("{0} {1}", c, Regex.IsMatch(c, p)); } } }
^[A-Za-z0-9][A-Za-z0-9\-]{4,13}[A-Za-z0-9]$ 5<长度<16
如何判断字符串str中是否只包括数字,如果不全是数字,只截取前面的数字!先谢了!
{
string str = this.TextBox2.Text.Trim();
System.Text.RegularExpressions.Regex strRegex = new Regex(@"[0-9]",RegexOptions.IgnoreCase);
//MatchCollection metches = strRegex.Matches(str);
if(strRegex.Matches(str).Count == str.Length)
{
Response.Write("<br>输入的全是数");
}
System.Text.RegularExpressions.Regex strRegex2 = new Regex(@"[a-z]",RegexOptions.IgnoreCase);
if(strRegex2.Matches(str).Count == str.Length)
{
Response.Write("输入的全是字母");
}
}
123sdfsdfd34343df,
如何能取出前面的123呢?
如果字符串中不全是数字,比如
123sdfsdfd34343df,
如何能取出前面的123呢?
str17 = Regex.Replace(str17,@"[^\d].*","");
System.Text.RegularExpressions.Regex strRegex = new Regex(@"[0-9]",RegexOptions.IgnoreCase);
if(strRegex.Matches(str).Count == str.Length)
{
Response.Write("<br>输入的全是数");
Response.Write(" "+str);
}
else
{
string pat = @"([0-9]+)";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(str); if (m.Success)
{ Group g = m.Groups[1];
CaptureCollection cc = g.Captures;
Capture c = cc[0];
if (c.Index == 0)
{
Response.Write("<br>输入的不全是数,前面的数字:");
Response.Write(" "+c);
}
}
}我也菜鸟一个.这个应该可以的,
using System.Text.RegularExpressions;
public class test
{
static void Main()
{
string p = @"^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])$";
string [] s = {"-", "abcd", "a-c", "-a"};
foreach(string c in s)
{
Console.WriteLine("{0} {1}", c, Regex.IsMatch(c, p));
}
}
}