本文整理汇总了C#中System.Text.RegularExpressions.Regex.IsMatch方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.IsMatch方法的具体用法?C# Regex.IsMatch怎么用?C# Regex.IsMatch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Text.RegularExpressions.Regex
的用法示例。
在下文中一共展示了Regex.IsMatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DataSet
public override void DataSet(string myPath, string myPattern)
{
string[] fileList = Directory.GetFiles(myPath, myPattern, SearchOption.AllDirectories);
Regex regexMov = new Regex(MovieContents.REGEX_MOVIE_EXTENTION, RegexOptions.IgnoreCase);
Regex regexJpg = new Regex(@".*\.jpg$|.*\.jpeg$", RegexOptions.IgnoreCase);
Regex regexLst = new Regex(@".*\.wpl$|.*\.asx$", RegexOptions.IgnoreCase);
foreach (string file in fileList)
{
listFileInfo.Add(new common.FileContents(file, myPath));
if (regexMov.IsMatch(file))
MovieCount++;
if (regexJpg.IsMatch(file))
ImageCount++;
if (regexLst.IsMatch(file))
ListCount++;
if (regexJpg.IsMatch(file) && ImageCount == 1)
StartImagePathname = file;
}
ColViewListFileInfo = CollectionViewSource.GetDefaultView(listFileInfo);
if (ColViewListFileInfo != null && ColViewListFileInfo.CanSort == true)
{
ColViewListFileInfo.SortDescriptions.Clear();
ColViewListFileInfo.SortDescriptions.Add(new SortDescription("FileInfo.LastWriteTime", ListSortDirection.Ascending));
}
}
示例2: addNumberItems
private void addNumberItems(ToolStripMenuItem s, bool addSubchildren)
{
ToolStripMenuItem item;
((ToolStripDropDownMenu)s.DropDown).ShowImageMargin = false;
if (s.DropDownItems.Count == 0)
{
Regex rx = new Regex("^[0-9]+$");
int start = rx.IsMatch(s.Text) ? 0 : 1;
for (int i = start; i < 10; i++)
{
item = new ToolStripMenuItem(string.Format("{0}{1}", rx.IsMatch(s.Text) ? s.Text : "", i));
item.DisplayStyle = ToolStripItemDisplayStyle.Text;
item.Padding = new Padding(0);
item.Margin = new Padding(0);
item.DropDownOpening += new EventHandler(ToolStripMenuItem_DropDownOpening);
item.Click += new EventHandler(ToolStripMenuItem_Click);
s.DropDownItems.Add(item);
}
}
// Check sub-children.
if (addSubchildren)
{
for (int i = 0; i < s.DropDownItems.Count; i++)
{
addNumberItems((ToolStripMenuItem)s.DropDownItems[i], false);
}
}
}
示例3: Placeholdit
/// <summary>
/// Generates a url pointing to the website placehold.it.
/// </summary>
/// <param name="size">The size of the image</param>
/// <param name="format">The format the image</param>
/// <param name="backgroundColor">The image background color.</param>
/// <param name="textColor">The image text/foreground color.</param>
/// <param name="text">The text on the image.</param>
/// <returns>The generated image.</returns>
/// <exception cref="ArgumentException">
/// <para>
/// If the <paramref name="size" /> is not in the format '300' and not in the format '300x300'.
/// </para>
/// <para>
/// If the background color is not a hex color value without '#'
/// </para>
/// <para>
/// If the text color is not a hex color value without '#'
/// </para>
/// </exception>
public static string Placeholdit(
string size = "300x300",
PlaceholditImageFormat format = PlaceholditImageFormat.png,
string backgroundColor = null,
string textColor = null,
string text = null)
{
if (!Regex.IsMatch(size, @"^[0-9]+(x[0-9]+)?$"))
throw new ArgumentException("size should be specified in format '300' or '300x300", "size");
var regex = new Regex("^(?:[A-Fa-f0-9]{3}|[A-fa-f0-9]{6})$");
if (backgroundColor != null && !regex.IsMatch(backgroundColor))
throw new ArgumentException("backgroundColor must be a hex value without '#'", "backgroundColor");
if (textColor != null && !regex.IsMatch(textColor))
throw new ArgumentException("textColor must be a hex value without '#'", "textColor");
var imageUrl = "https://placehold.it/" + size;
if (!string.IsNullOrEmpty(backgroundColor))
imageUrl += "/" + backgroundColor;
if (!string.IsNullOrEmpty(textColor))
{
if (string.IsNullOrEmpty(backgroundColor))
imageUrl += "/D3D3D3";
imageUrl += "/" + textColor;
}
imageUrl += "." + format;
if (!string.IsNullOrEmpty(text))
imageUrl += "?text=" + text;
return imageUrl;
}
示例4: functionCheck
/*
* Ham kiem tra chuoi
*/
public static bool functionCheck(string sNumber)
{
// Tach chuoi theo ' ' va dua vao mang moi
string[] sArray = new string[] { };
sArray = sNumber.Split(' ');
// Kiem tra cu phap chuoi
switch (sArray.Length)
{
case 2: // Dung cu phap
Regex regex = new Regex(@"^[0-9]*$");
bool flag1 = regex.IsMatch(sArray[0]);
bool flag2 = regex.IsMatch(sArray[1]);
if (flag1 && flag2) // So thu nhat dung - So thu hai dung
{
return true;
}
else
{
string error = "Thong bao\t- Loi dau vao: <";
if (!flag1 && !flag2) { error += sArray[0] + "> , <" + sArray[1]; } // So thu nhat sai - So thu hai sai
else if (!flag1) { error += sArray[0]; } // So thu nhat sai - So thu hai dung
else { error += sArray[1]; } // So thu nhat dung - So thu hai sai
error += "> khong hop le!";
Console.WriteLine(error);
}
break;
default: // Sai cu phap
Console.WriteLine("Thong bao\t- Loi dau vao: Sai cu phap!");
break;
}
return false;
}
示例5: Application_BeginRequest
private void Application_BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
foreach (var rule in GetRuleList())
{
var lookFor = "^" + ResolveUrl(app.Request.ApplicationPath, rule.LookFor) + "$";
var re = new Regex(lookFor, RegexOptions.IgnoreCase);
if (IsHttpUrl(rule.LookFor))
{
if (re.IsMatch(app.Request.Url.AbsoluteUri))
{
var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Url.AbsoluteUri, rule.SendTo));
RewritePath(app.Context, sendTo);
break;
}
}
else
{
if (re.IsMatch(app.Request.Path))
{
var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Path, rule.SendTo));
RewritePath(app.Context, sendTo);
break;
}
}
}
}
示例6: Test6
public void Test6()
{
var regex = new Regex(@"^//{1}[^0-9]+\n{1}");
Assert.Equal("//***\n", regex.Match("//***\n0***9***7").Value);
Assert.False(regex.IsMatch("/***\n0***9***7"));
Assert.False(regex.IsMatch("123//***\n0***9***7"));
}
示例7: Button_Click
private void Button_Click(object sender, RoutedEventArgs e)
{
string PrimerNumero = txtPrimerNumero.Text;
string SegundoNumero = txtSegundoNumero.Text;
string error = string.Empty;
Regex r = new Regex(@"^\d+$");
if (!r.IsMatch(PrimerNumero) && PrimerNumero[0] != '-')
{
error += " El primer valor introducido no es valido, verifique que sea un numero de menos de 500 digitos por favor/n";
}
if (!r.IsMatch(SegundoNumero) && SegundoNumero[0] != '-')
{
error += " El segundo valor introducido no es valido, verifique que sea un numero de menos de 500 digitos por favor/n";
}
if (error.Length > 0)
{
MessageBox.Show(error);
}
else
{
try
{
lblRespuesta.Text = delegadoKaratsuba.Multiplicar(PrimerNumero, SegundoNumero);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
示例8: btnNew_Click
private void btnNew_Click(object sender, RoutedEventArgs e)
{
var regexItem = new Regex("^[a-zA-Z ]*$");
String firstName = txtFirstName.Text;
String lastName = txtLastName.Text;
String team = cmbTeam.Text;
int price = 0;
if (regexItem.IsMatch(firstName) && regexItem.IsMatch(lastName) && Int32.TryParse(txtPrice.Text, out price))
{
if(!playerList.Any())
{
playerList.Add(new Player(firstName, lastName, team, price));
lblStatusBox.Text = "Pelaaja lisätty.";
}
else if(!Exists(firstName, lastName))
{
playerList.Add(new Player(firstName, lastName, team, price));
lblStatusBox.Text = "Pelaaja lisätty.";
}
else
{
lblStatusBox.Text = "Virhe: Pelaaja löytyy jo luettelosta.";
}
}
else
{
lblStatusBox.Text = "Virhe: Kentissä käytetty vääriä merkkejä!";
}
}
示例9: ValidClass
private bool ValidClass(CreateClassModel aCreateClassModel)
{
if (string.IsNullOrEmpty(aCreateClassModel.UniversityId) || aCreateClassModel.UniversityId.Equals(Constants.SELECT)) {
theValidationDictionary.AddError("UniversityId", aCreateClassModel.UniversityId, "A university is required.");
}
Regex myAlphaNumericRegex = new Regex("^[a-zA-Z0-9]+$");
if (!myAlphaNumericRegex.IsMatch(aCreateClassModel.ClassSubject)) {
theValidationDictionary.AddError("ClassSubject", aCreateClassModel.ClassSubject, "A class code must be provided and must be only letters and numbers.");
}
if (!myAlphaNumericRegex.IsMatch(aCreateClassModel.ClassCourse)) {
theValidationDictionary.AddError("ClassCourse", aCreateClassModel.ClassCourse, "A class code must be provided and must be only letters and numbers.");
}
if (string.IsNullOrEmpty(aCreateClassModel.ClassTitle)) {
theValidationDictionary.AddError("ClassTitle", aCreateClassModel.ClassTitle, "A class title must be provided.");
}
if (theClassRepository.GetClass(aCreateClassModel.ClassSubject, aCreateClassModel.ClassCourse) != null) {
theValidationDictionary.AddError("Class", string.Empty, "That class already exists.");
}
return theValidationDictionary.isValid;
}
示例10: MockDir
private void MockDir(DirectoryItem item)
{
directoryMock.Exists(item.FullPath).Returns(true);
var dirFiles = item.Children.OfType<FileItem>().ToList();
List<DirectoryItem> subDirs = item.Children.OfType<DirectoryItem>().ToList();
subDirs.ForEach(MockDir);
dirFiles.ForEach(f=>MockFile(item, f));
List<string> allFiles = dirFiles.Select(f => Path.Combine(item.FullPath, f.Name)).ToList();
directoryMock.EnumerateFiles(item.FullPath).Returns(allFiles);
directoryMock.EnumerateFiles(item.FullPath, Arg.Any<string>())
.Returns
((callInfo)=>
{
var searchPattern = (string)callInfo.Args()[1];
var regex = new Regex(WildcardToRegex(searchPattern));
return allFiles.Where(f => regex.IsMatch(f));
}
);
directoryMock.EnumerateFiles(item.FullPath, Arg.Any<string>(), SearchOption.AllDirectories)
.Returns(c =>
{
var files = new List<string>();
var searchPattern = (string)c.Args()[1];
var regex = new Regex(WildcardToRegex(searchPattern));
GetSubDirs(item).ForEach(sd => files.AddRange(directoryMock.EnumerateFiles(sd.FullPath, searchPattern)
.Where(f => regex.IsMatch(f))));
files.AddRange(allFiles.Where(f => regex.IsMatch(f)));
return files;
});
directoryMock.EnumerateDirectories(item.FullPath).Returns(subDirs.Select(_=>_.FullPath).ToList());
}
示例11: btnSave_Click
private void btnSave_Click(object sender, EventArgs e)
{
int messageShowSecond;
if(!int.TryParse(txtSecond.Text, out messageShowSecond))
{
MessageBox.Show("你输入的整数是错误的");
return;
}
Regex reg = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", RegexOptions.Compiled);
if(!reg.IsMatch(txtTelecomDns.Text))
{
MessageBox.Show("你输入的电信DNS IP格式不对");
return;
}
if (!reg.IsMatch(txtUnicomDns.Text))
{
MessageBox.Show("你输入的网通DNS IP格式不对");
return;
}
string encode = radUTF8.Checked ? "UTF-8" : "GB2312";
string linkQuickUse = radNoQuick.Checked ? "0" : "1";
string addMicroComment = radNoComment.Checked ? "0" : "1";
string saveComment = radDelComment.Checked ? "0" : "1";
string saveToSysDir = radSysDir.Checked ? "1" : "0";
string isFront = radFront.Checked ? "1" : "0";
HostsDal.SaveConfig(encode, linkQuickUse, addMicroComment, saveComment, saveToSysDir,
messageShowSecond, isFront, txtTelecomDns.Text, txtUnicomDns.Text);
this.Close();
}
示例12: Authenticate
/// <summary>
/// Authenticates the user
/// </summary>
/// <param name="user">user from login form</param>
/// <param name="password">password from login form</param>
public static bool Authenticate(String user,String password)
{
var positiveIntRegex = new Regex(@"^\w+$");
if (!positiveIntRegex.IsMatch(user))
{
return false;
}
if (!positiveIntRegex.IsMatch(password))
{
return false;
}
String encryptedPass = Encrypt(password);
string constr = Settings.Default.UserDbConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand command = new SqlCommand();
command.Connection = con;
command.Parameters.AddWithValue("@Username", user);
command.CommandText = "SELECT Password FROM Users WHERE Name = @Username";
command.CommandType = CommandType.Text;
con.Open();
string _password = "";
if (command.ExecuteScalar() != null)
_password = command.ExecuteScalar().ToString();
else
return false;
con.Close();
if (encryptedPass.Equals(_password))
{
return true;
}
return false;
}
示例13: Validate
public EmailValidationResult Validate(EmailReport report, ReportRule rule)
{
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(report.GetEmailMessage().Body);
var body = htmlDocument.DocumentNode.Find(HtmlElementType.Body).FirstOrDefault();
var blocks = htmlDocument.DocumentNode.Find("#block");
var tables = htmlDocument.DocumentNode.Find(HtmlElementType.Table);
var styleRegex = new Regex(@"background[\s]*:.*(!#fff|!#ffffff|white|transparent)");
var isVisibleColor = new Func<string, bool>(x =>
{
var value = x.ToLower();
var hiddenValues = new string[] { "#fff", "#ffffff", "white", "transparent" };
return !string.IsNullOrEmpty(value) && !hiddenValues.Any(y => value.Contains(y));
});
var valid = body == null ||
(body.Attributes.Any(x => x.Name.ToLower() == "bgcolor" && isVisibleColor(x.Value)) ||
body.Attributes.Any(x => x.Name.ToLower() == "style" && styleRegex.IsMatch(x.Value.ToLower())) ||
blocks.Any(block => block.Attributes.Any(x => x.Name.ToLower() == "style" && styleRegex.IsMatch(x.Value.ToLower()))) ||
blocks.Any(block => block.Attributes.Any(x => x.Name.ToLower() == "bgcolor" && isVisibleColor(x.Value))) ||
tables.Any(table => table.Attributes.Any(x => x.Name.ToLower() == "style" && styleRegex.IsMatch(x.Value.ToLower()))) ||
tables.Any(table => table.Attributes.Any(x => x.Name.ToLower() == "bgcolor" && isVisibleColor(x.Value))));
return new EmailValidationResult
{
Valid = valid,
ReportRule = rule
};
}
示例14: NextString
/// <summary>
/// Returns a randomly generated string of a specified length, containing
/// only a set of characters, and at max a specified number of non alpha numeric characters.
/// </summary>
/// <param name="length">Length of the string</param>
/// <param name="allowedCharacters">Characters allowed in the string</param>
/// <param name="numberOfNonAlphaNumericsAllowed">Number of non alpha numeric characters allowed.</param>
/// <returns>A randomly generated string of a specified length, containing only a set of characters, and at max a specified number of non alpha numeric characters.</returns>
public string NextString(int length, string allowedCharacters, int numberOfNonAlphaNumericsAllowed)
{
if (length < 1)
return "";
var tempBuilder = new StringBuilder();
var comparer = new Regex(allowedCharacters);
var alphaNumbericComparer = new Regex("[0-9a-zA-z]");
int counter = 0;
while (tempBuilder.Length < length)
{
var tempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
if (comparer.IsMatch(tempValue))
{
if (!alphaNumbericComparer.IsMatch(tempValue) && numberOfNonAlphaNumericsAllowed > counter)
{
tempBuilder.Append(tempValue);
++counter;
}
else if (alphaNumbericComparer.IsMatch(tempValue))
{
tempBuilder.Append(tempValue);
}
}
}
return tempBuilder.ToString();
}
示例15: TestCreditCardNumberRegex
public void TestCreditCardNumberRegex()
{
ContentPolicyReader cpr = new ContentPolicyReader();
List<ContentRule> contentRules = cpr.Read(contentPolicy);
Assert.AreEqual(4, contentRules.Count);
ContentRule personalInformationRule = contentRules[0];
Assert.AreEqual(3, personalInformationRule.Conditions.Count);
ContentCondition ccCondition = personalInformationRule.Conditions[0];
Assert.AreEqual(sReCCN, ccCondition.Regex);
Regex reCCN = new Regex(sReCCN);
// Ensure we correctly match valid credit card numbers
foreach (string sValidCCN in CreditCardNumberTestData.Valid)
{
Assert.IsTrue(reCCN.IsMatch(sValidCCN), "Expected to match a valid credit card number");
}
// Ensure we don't false positive on non-valid numbers
foreach (string sNonValidCCN in CreditCardNumberTestData.NonValid)
{
Assert.IsFalse(reCCN.IsMatch(sNonValidCCN), "Expected NOT to match a non-valid credit card number");
}
}