private string VerifSaisie(string numero) { Boolean plusEnPremier = false; String resultatfinal = ""; numero = numero.Trim(); //filtre regex on ne garde que ce qui est chiffre et '+' System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex("[^0-9+]"); string resultat1 = myRegex.Replace(numero, ""); if (resultat1.Length > 0)//Si le résultat du premier chiffre donne autre chose qu'une chainbe vide on continue { if (resultat1[0] == '+')//on verifie si le premier élement de la collection de caractére est un "+", si oui on valorise un booleen { plusEnPremier = true; } myRegex = new System.Text.RegularExpressions.Regex("[^0-9]");//on garde que les chiffres dans la chaine } //test du boleen si oui on rajoute le caractére '+' if (plusEnPremier) { resultatfinal = "+" + myRegex.Replace(resultat1, ""); } else { resultatfinal = myRegex.Replace(resultat1, ""); } return resultatfinal; //renvoi la chaine modifiée }
public static bool validarCorreo(string cadenaUsuario) { bool val = true; bool result = false; foreach (char c in cadenaUsuario) { if (c == '"') { val = false; break; } } if (val == true) { patron = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"; auto = new System.Text.RegularExpressions.Regex(patron); result = auto.IsMatch(cadenaUsuario); } else { result = false; } return result; }
/// <summary> /// Search Running Object Table for a running VisualStudio instance which has open a particular solution. /// Typical usage might be EnvDTE.Solution sln = DesignTime.GetVisualStudioInstanceBySolution(@"\\My Solution\.sln$") /// </summary> /// <param name="solution_file_regex">Regular expression matching the solution fullname</param> /// <returns>The Solution object if a match was found, null otherwise</returns> public static EnvDTE.Solution GetVisualStudioInstanceBySolution(string solution_file_regex) { System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(solution_file_regex); IRunningObjectTable runningObjectTable; GetRunningObjectTable(0, out runningObjectTable); IEnumMoniker monikerEnumerator; runningObjectTable.EnumRunning(out monikerEnumerator); monikerEnumerator.Reset(); IMoniker[] monikers = new IMoniker[1]; IntPtr numFetched = IntPtr.Zero; while (monikerEnumerator.Next(1, monikers, numFetched) == 0) { IBindCtx ctx; CreateBindCtx(0, out ctx); string runningObjectName; monikers[0].GetDisplayName(ctx, null, out runningObjectName); if (re.IsMatch(runningObjectName)) { object runningObjectVal; runningObjectTable.GetObject(monikers[0], out runningObjectVal); EnvDTE.Solution sln = runningObjectVal as EnvDTE.Solution; if (sln != null) return sln; } } return null; }
public static long getByteFromGMKBString(String text) { long result = 0; System.Text.RegularExpressions.Regex gbReg = new System.Text.RegularExpressions.Regex(@"(\d+)GB", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex kbReg = new System.Text.RegularExpressions.Regex(@"(\d+)KB", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex mbReg = new System.Text.RegularExpressions.Regex(@"(\d+)MB", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex bReg = new System.Text.RegularExpressions.Regex(@"(\d+)B", System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (bReg.IsMatch(text)) { var m = bReg.Match(text); result += long.Parse(m.Groups[1].Value); } if (kbReg.IsMatch(text)) { var m = kbReg.Match(text); result += long.Parse(m.Groups[1].Value) * BaseByte; } if (mbReg.IsMatch(text)) { var m = mbReg.Match(text); result += long.Parse(m.Groups[1].Value) * BaseByte * BaseByte; } if (gbReg.IsMatch(text)) { var m = gbReg.Match(text); result += long.Parse(m.Groups[1].Value) * BaseByte * BaseByte * BaseByte; } return result; }
/// <summary> /// Handling label_value_numeric /// </summary> public static Double ConvertToDouble(string s) { try { string result = ""; System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[1-9][0-9,.]*"); var arr = reg.Match(s).Value.Split('.'); if (arr.Length == 1) result = arr[0]; else result = arr[0] + "." + arr[1]; result = result.Trim('.'); if (String.IsNullOrWhiteSpace(result)) return 0; return Convert.ToDouble(result); } catch (Exception ex) { logger.Info("Error occured in ConvertToDouble for label_value_numeric - "+ex.Message); return 0; } }
private string GetOutput(string res, string file_name) { try { WebClient client = new WebClient(); NameValueCollection form = new NameValueCollection(); form.Add("login", Properties.Settings.Default.login); form.Add("token", Properties.Settings.Default.api); form.Add(String.Format("file_ext[{0}]", file_name), Path.GetExtension(file_name)); form.Add(String.Format("file_name[{0}]", file_name),file_name ); form.Add(String.Format("file_contents[{0}]", file_name), res); byte[] responseData = client.UploadValues(API_URL, form); String s = Encoding.UTF8.GetString(responseData); System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\"repo\":\"(\\d+)\""); System.Text.RegularExpressions.Match m = r.Match(s); if(m.Success){ return String.Format("<script src=\"http://gist.github.com/{0}.js\"></script>", m.Groups[1].Value); } return null; } catch (Exception webEx) { Console.WriteLine(webEx.ToString()); } return null; }
/// <summary> /// 清除HTML代码 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string CleanHTML(string text) { var regex = new System.Text.RegularExpressions.Regex(@"(<[a-zA-Z].*?>)|(<[\/][a-zA-Z].*?>)"); var content = regex.Replace(text, string.Empty); content = content.Replace(" ", " "); return content; }
/// <summary> /// Default constructor that registers default content handlers /// </summary> public RestClient() { var asmName = this.GetType().AssemblyQualifiedName; var versionExpression = new System.Text.RegularExpressions.Regex("Version=(?<version>[0-9.]*)"); var m = versionExpression.Match(asmName); if (m.Success) { version = new Version(m.Groups["version"].Value); } ContentHandlers = new Dictionary<string, IDeserializer>(); AcceptTypes = new List<string>(); DefaultParameters = new List<Parameter>(); // register default handlers AddHandler("application/json", new JsonDeserializer()); AddHandler("application/xml", new XmlDeserializer()); AddHandler("text/json", new JsonDeserializer()); AddHandler("text/x-json", new JsonDeserializer()); AddHandler("text/javascript", new JsonDeserializer()); AddHandler("text/xml", new XmlDeserializer()); AddHandler("*", new XmlDeserializer()); FollowRedirects = true; }
/// <summary> /// Html到文本 /// </summary> /// <param name="Html"></param> /// <param name="html"></param> /// <returns></returns> public static string Html2String(this HtmlHelper Html, string html) { System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[/s/S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[/s/S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[/s/S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[/s/S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[/s/S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"/<img[^/>]+/>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset html = regex6.Replace(html, ""); //过滤frameset html = regex7.Replace(html, ""); //过滤frameset html = regex8.Replace(html, ""); //过滤frameset html = regex9.Replace(html, ""); html = html.Replace(" ", " "); html = html.Replace("</strong>", ""); html = html.Replace("<strong>", ""); return html; }
public void TestBodyAnswerParcer() { string testAnswer = "<123:-22 NOSENSOR>"; var answerParceRegX = new System.Text.RegularExpressions.Regex(ANSWERPARCE_EXPR, System.Text.RegularExpressions.RegexOptions.Compiled); var match = answerParceRegX.Match(testAnswer); if (!match.Success) throw new Exception("Error parcing answer"); string body = match.Groups["BODY"].Value; if (body == "OK") Assert.Fail(); else { var bodyParcerRegX = new System.Text.RegularExpressions.Regex(BODYPARCE_EXPR, System.Text.RegularExpressions.RegexOptions.Compiled); var matchArg = bodyParcerRegX.Match(body); if (!matchArg.Success) Assert.Fail(); foreach (System.Text.RegularExpressions.Capture argument in matchArg.Groups["ARG"].Captures) { if (argument.Value != "-22" & argument.Value != "NOSENSOR") Assert.Fail(); } } }
public RegexTermEnum(IndexReader reader, Term term) : base() { field = term.Field(); System.String text = term.Text(); pattern = new Pattern(text); // Find the first regex character position, to find the // maximum prefix to use for term enumeration int index = 0; while (index < text.Length) { char c = text[index]; if (!System.Char.IsLetterOrDigit(c)) break; index++; } pre = text.Substring(0, (index) - (0)); SetEnum(reader.Terms(new Term(term.Field(), pre))); }
private static string ReplaceFileIDRecycleNames(string metafileText, string oldPrefix, string newPrefix) { string fileIDPattern = "([\\d]{8}: )" + oldPrefix; var fileIDRegex = new System.Text.RegularExpressions.Regex(fileIDPattern); string replacementText = "$1" + newPrefix; return fileIDRegex.Replace(metafileText, replacementText); }
private static string ReplaceSpriteMetaData(string metafileText, string oldPrefix, string newPrefix) { string spritenamePattern = "(- name: )" + oldPrefix; var spritenameRegex = new System.Text.RegularExpressions.Regex(spritenamePattern); string replacementText = "$1" + newPrefix; return spritenameRegex.Replace(metafileText, replacementText); }
protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); // 只读, 不处理 if (this.ReadOnly) return; string regex = @"^[\w ]+$"; //匹配数字、字母、汉字 if (isNumber) regex = "^[0-9]*$"; //匹配数字 var reg = new System.Text.RegularExpressions.Regex(regex);// var str = this.Text.Replace(" ", ""); var sb = new StringBuilder(); if (!reg.IsMatch(str)) { for (int i = 0; i < str.Length; i++) { if (reg.IsMatch(str[i].ToString())) { sb.Append(str[i].ToString()); } } this.Text = sb.ToString(); this.SelectionStart = this.Text.Length; //定义输入焦点在最后一个字符 } }
public bool ValidateEmail() { bool result = true; try { if (txtMailId.Text.Trim() != string.Empty) { System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");//^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$ if (txtMailId.Text.Length > 0) { if (!rEMail.IsMatch(txtMailId.Text)) { MessageBox.Show("Invalid Email", "Pharmasoft", MessageBoxButtons.OK, MessageBoxIcon.Information); result = false; txtMailId.Focus(); } } } } catch (Exception ex) { MessageBox.Show("SM" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return result; }
private string createResponse(string rawline) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(GET )(/)([^ ]+)"); var result = regex.Match(rawline); if (result.Success && result.Groups.Count == 4) { string command = result.Groups[3].Value; string headers = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Accept-Ranges: bytes\r\n" + "Vary: Accept-Encoding\r\n"; if (command == "get_server_data") { string response = "name=" + Server.instance.config.getString("server_name") + "\nmax_players=" + Server.instance.config.getString("max_players") + "\ngame_port=" + Server.instance.config.getString("game_port") + "\nplayers=" + Server.instance.playerpool.Count; return headers + "Content-Length: " + response.Length + "\r\n\r\n" + response + "\r\n\r\n"; } } else { string headers = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/HTML\r\n" + "Accept-Ranges: bytes\r\n" + "Vary: Accept-Encoding\r\n" + "refresh:5;url=http://gta.vdgtech.eu\r\n\r\nThat command is invalid. Redirecting to gta.vdgtech.eu in 5 seconds.\r\n\r\n"; return headers; } return null; }
protected void Page_Load(object sender, EventArgs e) { ////get the expired cookie //System.Web.Security.FormsAuthentication.SignOut(); ////set the cookie Domain //HttpCookie lcookie2 = Context.Response.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]; //lcookie2.Domain = Core.Global.CookieDomain; OnlineUserBlock.Components.oluMonitor.MemberSignout(); Session.Clear(); if (Request.Cookies["sid"] != null || Request.Cookies["sso"] != null) { Response.Cookies["sid"].Expires = DateTime.Now; Response.Cookies["sso"].Expires = DateTime.Now;//单点登录的Cookie } string url = CY.Utility.Common.RequestUtility.GetCookieValue("CurrentUrl"); Response.Cookies["CurrentUrl"].Expires = DateTime.Now;//用户访问过的上个页面地址 System.Text.RegularExpressions.Regex R = new System.Text.RegularExpressions.Regex("(" + url + ")+"); //查找"Abc" System.Text.RegularExpressions.Match M = R.Match("Logout.aspx"); //设定要查找的字符串 if (M.Index > 0 || url.Length <= 4) { Page.ClientScript.RegisterStartupScript(this.GetType(), "logout", "<script type='text/javascript'>window.location.href='Login.aspx';</script>"); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "logout", "<script type='text/javascript'>window.location.href='" + url + "';</script>"); } }
private string GetLanguageFromHighlightClassAttribute(HtmlNode node) { string val = node.GetAttributeValue("class", ""); var rx = new System.Text.RegularExpressions.Regex("highlight-([a-zA-Z0-9]+)"); var res = rx.Match(val); return res.Success ? res.Value : ""; }
public string GetTableName(Type entityType) { var sql = this.Set(entityType).ToString(); var regex = new System.Text.RegularExpressions.Regex(@"FROM \[dbo\]\.\[(?<table>.*)\] AS"); var match = regex.Match(sql); return match.Groups["table"].Value; }
/// <summary> /// 获取双色球开奖结果 /// </summary> /// <returns></returns> private void GetSSQResult() { string ssqResult = ""; try { System.Threading.Thread.Sleep(3000); string html = new System.Net.WebClient().DownloadString("http://www.zhcw.com/kaijiang/index_kj.html"); html = html.Substring(html.IndexOf("<dd>"), html.IndexOf("</dd>") - html.IndexOf("<dd>") + 4).Replace("\r\n",""); string regStr = "<li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiublud\">(.*?)</li>"; var regex = new System.Text.RegularExpressions.Regex(regStr); System.Text.RegularExpressions.Match m; if ((m = regex.Match(html)).Success && m.Groups.Count == 8) { for (int i = 1; i < 8; i++) { ssqResult += "," + m.Groups[i].Value; } ssqResult = ssqResult.Substring(1); } } catch (Exception ex) { ssqResult = ex.Message; } Response.Write(ssqResult); Response.Flush(); Response.End(); }
private string GetLanguageFromConfluenceClassAttribute(HtmlNode node) { string val = node.GetAttributeValue("class", ""); var rx = new System.Text.RegularExpressions.Regex(@"brush:\s?(:?.*);"); var res = rx.Match(val); return res.Success ? res.Value : ""; }
private void btnTest_Click(object sender, EventArgs e) { if (txtRegEx.Text.Trim().Length == 0) { MessageBox.Show("Regular Expression is empty", "Test Regular Expression", MessageBoxButtons.OK, MessageBoxIcon.Error); txtRegEx.Focus(); return; } System.Text.RegularExpressions.Regex rx; try { rx = new System.Text.RegularExpressions.Regex(txtRegEx.Text.Trim()); } catch { MessageBox.Show("Invalid regular expression", "Test Regular Expression", MessageBoxButtons.OK, MessageBoxIcon.Error); txtRegEx.Focus(); return; } string s = Microsoft.VisualBasic.Interaction.InputBox("Enter domain name to test:", "Test Regular Expression", LastTestStr).Trim(); if (s.Length == 0) return; LastTestStr = s.ToLower(); if (rx.IsMatch(LastTestStr)) { MessageBox.Show("TEST SUCCESSFUL\n\nDomain name matches regular expression", "Test Regular Expression", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("TEST FAILED\n\nDomain name does NOT match regular expression", "Test Regular Expression", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public static string GetDefaultDomain(string tnsNamePath) { if (string.IsNullOrEmpty(tnsNamePath)) return ""; if (File.Exists(tnsNamePath) == false) return ""; tnsNamePath = tnsNamePath.ToLower(); if (tnsNamePath.LastIndexOf("tnsnames.ora") < 0) return ""; string sqlnetora = tnsNamePath.Replace("tnsnames.ora", "sqlnet.ora"); if (File.Exists(sqlnetora) == false) return ""; try { string sqlnet = File.ReadAllText(sqlnetora); var reg = new System.Text.RegularExpressions.Regex(@"([#]*)[\t\ ]*NAMES.DEFAULT_DOMAIN\s*=\s*([a-zA-Z0-9_.]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); var m = reg.Match(sqlnet); if (m.Success) { if (m.Groups.Count >= 3) { if (m.Groups[1].Value != null && m.Groups[1].Value.IndexOf('#') >= 0) return ""; if (m.Groups[2].Value == null) return ""; return m.Groups[2].Value.Trim().ToUpper(); } } return ""; } catch { return ""; } }
/// <summary> /// このクラスでの実行すること。 /// </summary> /// <param name="runChildren"></param> public override void Run(bool runChildren) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("<input [^>]*>"); System.Text.RegularExpressions.Regex r2 = new System.Text.RegularExpressions.Regex(@"(\w)*\s*=\s*"+"\"([^\"]*)\""); var p = this.GetAncestorRawler().OfType<Page>(); if (p.Any() == false) { ReportManage.ErrReport(this, "上流にPageがありません"); return; } var page = p.First(); List<KeyValue> list = new List<KeyValue>(); foreach (System.Text.RegularExpressions.Match item in r.Matches(GetText())) { var dic = GetParameter(item.Value); if (dic.ContainsKey("type") && dic["type"] == "hidden") { if (dic.ContainsKey("name") && dic.ContainsKey("value")) { page.AddParameter(dic["name"], dic["value"]); list.Add(new KeyValue() { Key = dic["name"], Value = dic["value"] }); } } } base.Run(runChildren); }
public static IUnaryOperator Parse(ISyntaxNode parent, ref string Input, IRightValue firstOperand) { string temp = Input; Pattern regExPattern = "^\\s*" + new Group("def", "(\\+|-|!|~|\\*|&)");//|\\("+Provider.type+"\\) System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern); System.Text.RegularExpressions.Match match = regEx.Match(Input); if (!match.Success) { Input = temp; return null; } Input = Input.Remove(0, match.Index + match.Length); string Operator = match.Groups["def"].Value; switch (Operator) { default: Input = temp; throw new NotImplementedException(); } }
private static string HandleCreateAccount(HttpServer server, HttpListenerRequest request, Dictionary<string, string> parameters) { if (!parameters.ContainsKey("username")) throw new Exception("Missing username."); if (!parameters.ContainsKey("password")) throw new Exception("Missing password."); string username = parameters["username"]; string password = parameters["password"]; if (Databases.AccountTable.Count(a => a.Username.ToLower() == username.ToLower()) > 0) return JsonEncode("Username already in use!"); System.Text.RegularExpressions.Regex invalidCharacterRegex = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]"); if (invalidCharacterRegex.IsMatch(username)) return JsonEncode("Invalid characters detected in username!"); Random getrandom = new Random(); String token = getrandom.Next(10000000, 99999999).ToString(); AccountEntry entry = new AccountEntry(); entry.Index = Databases.AccountTable.GenerateIndex(); entry.Username = username; entry.Password = password; entry.Verifier = ""; entry.Salt = ""; entry.RTW_Points = 0; entry.IsAdmin = 0; entry.IsBanned = 0; entry.InUse = 0; entry.extrn_login = 0; entry.CanHostDistrict = 1; entry.Token = token; Databases.AccountTable.Add(entry); Log.Succes("HTTP", "Successfully created account '" + username + "'"); return JsonEncode("Account created!\n\nYour token is: " + token + ".\nCopy and paste given token in \"_rtoken.id\" file and put it in the same folder where your \"APB.exe\" is located."); }
private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { String filePath = openFileDialog1.FileName; openFileDialog1.InitialDirectory = filePath; mobiles.Clear(); listBox1.Items.Clear(); if (File.Exists(filePath)){ using (StreamReader sr = File.OpenText(filePath)) { string s = ""; while ((s = sr.ReadLine()) != null) { System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$"); if (s.Length == 11&& rex.IsMatch(s)) { if (!mobiles.Contains(s)) { mobiles.Add(s); listBox1.Items.Add(s); } } } } } msgLab.Text = "你将给 " + mobiles.Count + " 个人群发信息,短信字数共计为 " + contentTxt.Text.Length + " 个"; }
/// 过滤html,js,css代码 /// <summary> /// 过滤html,js,css代码 /// </summary> /// <param name="html">参数传入</param> /// <returns></returns> public static string CheckStr(string html) { System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script. *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script. *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe. *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); html = regex1.Replace(html, ""); //过滤<script></script>标记 html = regex2.Replace(html, ""); //过滤href=java script. (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset html = regex6.Replace(html, ""); //过滤frameset html = regex7.Replace(html, ""); //过滤frameset html = regex8.Replace(html, ""); //过滤frameset html = regex9.Replace(html, ""); html = html.Replace(" ", ""); html = html.Replace("</strong>", ""); html = html.Replace("<strong>", ""); html = html.Replace("'", "'"); return html; }
public NumberRange(string range) : this() { if (String.IsNullOrEmpty(range)) return; if (regex == null) regex = new System.Text.RegularExpressions.Regex("[0-9][0-9]*"); int matchNumber = 1; foreach (System.Text.RegularExpressions.Match match in regex.Matches(range)) { switch (matchNumber) { case 1: minimum = maximum = System.Convert.ToInt32(match.Value); break; case 2: maximum = System.Convert.ToInt32(match.Value); break; default: throw new Exception("Invalid number range \"" + range + "\"."); } matchNumber++; } if(matchNumber == 1) throw new Exception("Invalid number range \"" + range + "\"."); isSet = true; }
/// <summary> /// ajax method for chek routing /// </summary> /// <param name="pattern"></param> /// <param name="replaceStr"></param> public void CheckRouting(string pattern, string replaceStr) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern); string flag = reg.IsMatch(replaceStr) ? "匹配" : "不匹配"; RenderText(flag); CancelView(); }
/// <summary> /// 编辑用户 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnEdit_Click(object sender, EventArgs e) { UserInfo u = new UserInfo(); if (Operate == OperateType.Update) { u = UserManager.GetUser(UserId); } else { u.CommentCount = 0; u.CreateDate = DateTime.Now; u.PostCount = 0; u.UserName = StringHelper.HtmlEncode(txtUserName.Text.Trim()); } u.Email = StringHelper.HtmlEncode(txtEmail.Text.Trim()); u.SiteUrl = string.Empty; // StringHelper.HtmlEncode(txtSiteUrl.Text.Trim()); u.Status = chkStatus.Checked ? 1 : 0; u.Description = string.Empty; // StringHelper.TextToHtml(txtDescription.Text); u.Type = StringHelper.StrToInt(ddlUserType.SelectedValue, 0); u.Name = StringHelper.HtmlEncode(txtNickName.Text.Trim()); u.AvatarUrl = string.Empty; u.Displayorder = StringHelper.StrToInt(txtDisplayOrder.Text, 1000); if (!string.IsNullOrEmpty(txtPassword.Text.Trim())) { u.Password = StringHelper.GetMD5(txtPassword.Text.Trim()); } if (!string.IsNullOrEmpty(txtPassword.Text.Trim()) && txtPassword.Text != txtPassword2.Text) { ShowError("两次密码输入不相同!"); return; } if (Operate == OperateType.Update) { UserManager.UpdateUser(u); // 如果修改自己,更新COOKIE if (!string.IsNullOrEmpty(txtPassword.Text.Trim()) && u.UserId == PageUtils.CurrentUserId) { PageUtils.WriteUserCookie(u.UserId, u.UserName, u.Password, 0); } Response.Redirect("userlist.aspx?result=2"); } else { //System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[A-Za-z0-9\u4e00-\u9fa5-]"); //if (!reg.IsMatch(u.UserName)) //{ // ShowError("用户名不合法!"); // return; //} if (string.IsNullOrEmpty(u.UserName)) { ShowError("请输入登陆用户名!"); return; } System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[A-Za-z0-9\u4e00-\u9fa5-]"); if (!reg.IsMatch(u.UserName)) { ShowError("用户名限字母,数字,中文,连字符!"); return; } if (StringHelper.IsInt(u.UserName)) { ShowError("用户名不能为全数字!"); return; } if (string.IsNullOrEmpty(u.Password)) { ShowError("请输入密码!"); return; } if (UserManager.ExistsUserName(u.UserName)) { ShowError("该登陆用户名已存在,请换之"); return; } u.UserId = UserManager.InsertUser(u); Response.Redirect("userlist.aspx?result=1"); } }
/// <summary> /// Adds the page route. If the route name already exists then the PageAndRouteId obj will be added to the DataTokens "PageRoutes" List. /// </summary> /// <param name="routes">The routes.</param> /// <param name="routeName">Name of the route.</param> /// <param name="pageAndRouteId">The page and route identifier.</param> public static void AddPageRoute(this Collection <RouteBase> routes, string routeName, Rock.Web.PageAndRouteId pageAndRouteId) { Route route; List <Route> filteredRoutes = new List <Route>(); // The list of Route Names being used is case sensitive but IIS's usage of them is not. This can cause problems when the same // route name is used on different Rock sites. In order for the correct route to be selected they must be group together. // So we need to check if an existing route has been created first and then add to the data tokens if it has. foreach (var rb in routes) { // Make sure this is a route if (rb.GetType() == typeof(Route)) { Route r = rb as Route; filteredRoutes.Add(r); } } /* * 2020-02-12 ETD * Rock needs to compare routes and group them for the domain matching logic. The same route on two or more different sites * need to be group together under one route, with each page-route having a DataToken in that route. Since IIS only matches * the static portion of the route Rock must also only match the static portion of the route. A simple string compare will * not work since a variable name can vary and create two different routes instead of one grouped route. e.g. one site * has entity/{id} and another has entity/{guid}. * * While the variable name is not significant their existance is. So before comparing two routes to see if they are * the same Rock will first remove the contents of the brackets. e.g. checkin/{KioskId}/{CheckinConfigId}/{GroupTypeIds} * is converted to checkin/{}/{}/{}. Then a case insensitive compare is done between the routes. This removes the * possible variations in variable names and allows the static contents to be compared and the routes grouped correctly. * * Note: Since grouped routes are under the same URL only the first one is displayed in RouteTable.Routes. * So in this example both pages are grouped under the route URL entity/{id}. In the UI they are * still displayed as seperate routes since it is two different PageRoute objects. * * This was done to resolve issue: https://github.com/SparkDevNetwork/Rock/issues/4102 */ var reg = new System.Text.RegularExpressions.Regex(@"\{.*?\}"); var routeNameReg = reg.Replace(routeName, "{}"); if (filteredRoutes.Where(r => string.Compare(reg.Replace(r.Url, "{}"), routeNameReg, true) == 0).Any()) { route = filteredRoutes.Where(r => string.Compare(reg.Replace(r.Url, "{}"), routeNameReg, true) == 0).First(); var pageRoutes = (List <Rock.Web.PageAndRouteId>)route.DataTokens["PageRoutes"]; if (pageRoutes == null) { route.DataTokens.Add("PageRoutes", pageAndRouteId); } else { pageRoutes.Add(pageAndRouteId); } } else { var pageRoutes = new List <Rock.Web.PageAndRouteId>(); pageRoutes.Add(pageAndRouteId); route = new Route(routeName, new Rock.Web.RockRouteHandler()); route.DataTokens = new RouteValueDictionary(); route.DataTokens.Add("RouteName", routeName); route.DataTokens.Add("PageRoutes", pageRoutes); routes.Add(route); } }
public static void ExtractTextures(this ScriptedImporter importer, string dirName, Func <string, VrmLib.Model> CreateModel, Action onComplited = null) { if (string.IsNullOrEmpty(importer.assetPath)) { return; } var subAssets = importer.GetSubAssets <UnityEngine.Texture2D>(importer.assetPath); var path = string.Format("{0}/{1}.{2}", Path.GetDirectoryName(importer.assetPath), Path.GetFileNameWithoutExtension(importer.assetPath), dirName ); importer.SafeCreateDirectory(path); Dictionary <VrmLib.ImageTexture, string> targetPaths = new Dictionary <VrmLib.ImageTexture, string>(); // Reload Model var model = CreateModel(importer.assetPath); var mimeTypeReg = new System.Text.RegularExpressions.Regex("image/(?<mime>.*)$"); int count = 0; foreach (var texture in model.Textures) { var imageTexture = texture as VrmLib.ImageTexture; if (imageTexture == null) { continue; } var mimeType = mimeTypeReg.Match(imageTexture.Image.MimeType); var assetName = !string.IsNullOrEmpty(imageTexture.Name) ? imageTexture.Name : string.Format("{0}_img{1}", model.Root.Name, count); var targetPath = string.Format("{0}/{1}.{2}", path, assetName, mimeType.Groups["mime"].Value); imageTexture.Name = assetName; if (imageTexture.TextureType == VrmLib.Texture.TextureTypes.MetallicRoughness || imageTexture.TextureType == VrmLib.Texture.TextureTypes.Occlusion) { var subAssetTexture = subAssets.Where(x => x.name == imageTexture.Name).FirstOrDefault(); File.WriteAllBytes(targetPath, subAssetTexture.EncodeToPNG()); } else { File.WriteAllBytes(targetPath, imageTexture.Image.Bytes.ToArray()); } AssetDatabase.ImportAsset(targetPath); targetPaths.Add(imageTexture, targetPath); count++; } EditorApplication.delayCall += () => { foreach (var targetPath in targetPaths) { var imageTexture = targetPath.Key; var targetTextureImporter = AssetImporter.GetAtPath(targetPath.Value) as TextureImporter; targetTextureImporter.sRGBTexture = (imageTexture.ColorSpace == VrmLib.Texture.ColorSpaceTypes.Srgb); if (imageTexture.TextureType == VrmLib.Texture.TextureTypes.NormalMap) { targetTextureImporter.textureType = TextureImporterType.NormalMap; } targetTextureImporter.SaveAndReimport(); var externalObject = AssetDatabase.LoadAssetAtPath(targetPath.Value, typeof(UnityEngine.Texture2D)); importer.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(UnityEngine.Texture2D), imageTexture.Name), externalObject); } //AssetDatabase.WriteImportSettingsIfDirty(assetPath); AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate); if (onComplited != null) { onComplited(); } }; }
/// <summary> /// Load the saved plugin settings from disk. /// </summary> /// <returns>True if successfully loaded.</returns> public bool LoadPluginData() { // First check if settings pref file exists string settingsFilePath = SettingsFilePath(); if (!HEU_Platform.DoesFileExist(settingsFilePath)) { // Try reading from EditorPrefs to see if this is still using the old method return ReadFromEditorPrefs(); } // Open file and read each line to create the settings entry using (StreamReader reader = new StreamReader(settingsFilePath)) { // Must match first line string line = reader.ReadLine(); if (string.IsNullOrEmpty(line) || !line.Equals(PluginSettingsLine1)) { Debug.LogWarningFormat("Unable to load Plugin settings file. {0} should have line 1: {1}", settingsFilePath, PluginSettingsLine1); return false; } // Must match 2nd line line = reader.ReadLine(); if (string.IsNullOrEmpty(line) || !line.StartsWith(PluginSettingsLine2)) { Debug.LogWarningFormat("Unable to load Plugin settings file. {0} should start line 2 with: {1}", settingsFilePath, PluginSettingsLine2); return false; } Dictionary<string, StoreData> storeMap = new Dictionary<string, StoreData>(); string keyStr; string typeStr; string valueStr; DataType dataType; // "key(type)=value" System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(\w+)\((\w+)\)=(.*)"); while ((line = reader.ReadLine()) != null) { System.Text.RegularExpressions.Match match = regex.Match(line); if (match.Success && match.Groups.Count >= 4) { keyStr = match.Groups[1].Value; typeStr = match.Groups[2].Value; valueStr = match.Groups[3].Value; if (!string.IsNullOrEmpty(keyStr) && !string.IsNullOrEmpty(typeStr) && !string.IsNullOrEmpty(valueStr)) { try { dataType = (DataType)System.Enum.Parse(typeof(DataType), typeStr); StoreData store = new StoreData(); store._type = dataType; store._valueStr = valueStr; storeMap.Add(keyStr, store); } catch (System.Exception ex) { Debug.LogErrorFormat("Invalid data type found in settings: {0}. Exception: {1}", typeStr, ex.ToString()); } } } } _dataMap = storeMap; } return true; }
/// <summary> /// ストリームからイベントを配置するスクリプトコードを読み込み、イベントリストを返します。 /// ストリームの現在位置が1行目がイベントを配置する関数である必要があります。 /// </summary> public static List <EventOneData> DoLoadEVSetFunction(StreamReader R) { int index; var evIndex = -1; var buf = R.ReadLine(); var list = new List <EventOneData>(); //関数の終わりまで読み込む while (buf != "}") { index = buf.IndexOf(Resources.SQ_EVSetCommand); if (index != -1) { //イベントを配置する関数がヒット buf = buf.Replace("\t", "").Trim().Substring(Resources.SQ_EVSetCommand.Length); var reg = new System.Text.RegularExpressions.Regex(Resources.Regux_ArgumentList); var regMatch = reg.Matches(buf); if (regMatch.Count > 0) { //引数リストだけを抜粋する buf = regMatch[0].Groups["here"].Value; var spl = buf.Split(Resources.Split_Argument.ToCharArray()); //イベント名を抜き出す buf = buf.Substring(buf.IndexOf(",\"") + 2); buf = buf.Substring(0, buf.Length - 2).Replace("\\\"", "\"").Replace("\\\\", "\\"); var evData = new MapOneData.EventOneData( int.Parse(spl[1]), buf, new Point(int.Parse(spl[2]), int.Parse(spl[3])) ); evData.Pages.Clear(); evData.FixedID = int.Parse(spl[0]); list.Add(evData); evIndex = list.Count - 1; } buf = R.ReadLine(); continue; } index = buf.IndexOf(Resources.SQ_EVPageSetCommand); if (index != -1) { //イベントページを追加する関数がヒット buf = buf.Replace("\t", "").Trim().Substring(Resources.SQ_EVPageSetCommand.Length); var reg = new System.Text.RegularExpressions.Regex(Resources.Regux_ArgumentList); var regMatch = reg.Matches(buf); //引数リストだけを抜粋する buf = regMatch[0].Groups["here"].Value; var spl = buf.Split(Resources.Split_Argument.ToCharArray()); var evPage = new MapOneData.EventOneData.EventOnePage(); //両端のダブルクォートを排除する for (var i = 0; i < spl.Length; i++) { if (i == 2) { //グラフィック名のときは末尾の ) を先に取る spl[i] = spl[i].Substring(0, spl[i].Length - 1); } spl[i] = Common.CutDoubleQuotation(spl[i]); } var sub = spl[1].Split(Resources.Split_IDNamePair.ToCharArray()); evPage.Trigger = (Map.EventTriggerType) int.Parse(sub[0]); evPage.MoveType = (Map.EventMoveType) int.Parse(sub[1]); evPage.Direction = (Map.Direction4) int.Parse(sub[2]); evPage.MoveSpeed = (Map.Speed) int.Parse(sub[3]); evPage.MoveFrequency = (Map.Speed) int.Parse(sub[4]); evPage.AnimationPattern = (Map.EventAnimation) int.Parse(sub[5]); evPage.DrawPriority = (Map.EventDrawPriority) int.Parse(sub[6]); evPage.HitRect = new Size(int.Parse(sub[7]), int.Parse(sub[8])); evPage.StoppingAnimation = (int.Parse(sub[9]) == DX.TRUE) ? true : false; evPage.MovingAnimation = (int.Parse(sub[10]) == DX.TRUE) ? true : false; evPage.NoHit = (int.Parse(sub[11]) == DX.TRUE) ? true : false; evPage.FixedDirection = (int.Parse(sub[12]) == DX.TRUE) ? true : false; evPage.Graphic = spl[2].Replace("\\\"", "\"").Replace("\\\\", "\\"); list[evIndex].Pages.Add(evPage); } buf = R.ReadLine(); continue; } return(list); }
/// <summary> /// Formats the inside params. /// </summary> /// <param name="where">The where.</param> /// <returns></returns> private static string FormatInsideParams(string where) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"(@[\w\d_]+)"); return(r.Replace(where, "$1Inside", int.MaxValue)); }
// 网络调试:打开服务器 private void net_bt_opennet_Click(object sender, EventArgs e) { //检查IP地址输入格式是否正确 String regx = @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))"; System.Text.RegularExpressions.Regex check = new System.Text.RegularExpressions.Regex(regx); if (!check.IsMatch(net_tb_localip.Text)) { MessageBox.Show("本地IP地址输入错误,请重新输入!", "警告"); return; } //检查端口号是否为空 if (net_tb_localport.Text.Equals("")) { MessageBox.Show("请输入本地端口号!", "警告"); return; } //建立Socket连接 try { if (hostSocket == null) { hostSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); hostSocket.Bind(new IPEndPoint(IPAddress.Parse(net_tb_localip.Text), Convert.ToInt32(net_tb_localport.Text))); //设置 监听队列 长度为50(同时能够处理 50个连接请求) hostSocket.Listen(50); showTip1.Text = "服务器已启动,开始监听"; //开始接受客户端连接请求 //HostSocket.BeginAccept(new AsyncCallback(ClientAccepted), HostSocket); isWatch = true; threadWatch = new Thread(ClientAccepted0); threadWatch.IsBackground = true; threadWatch.Start(); showTip1.Text = "服务器已启动,开始接收数据"; showTip2.Text = "建立连接:0"; net_bt_opennet.Enabled = false; net_bt_closenet.Enabled = true; SystemConfig.WriteConfigData("LocalPort", net_tb_localport.Text.Trim()); SystemConfig.WriteConfigData("LocalIP", net_tb_localip.Text.Trim()); net_tb_localip.Enabled = false; net_tb_localport.Enabled = false; net_btnSend.Enabled = true; net_btnSendAll.Enabled = true; net_tx_send.Enabled = true; hasOpen = true; MainForms.ServerChange = true; } } catch (Exception) { MessageBox.Show("本地IP地址错误或端口已被占用!", "警告"); return; } }
private bool IsTextNumeric(string str) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]"); return(reg.IsMatch(str)); }
private bool WhiteList(string text) { var positiveExp = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9]*$"); return(positiveExp.IsMatch(text)); }
public static string CombineByPascalCase(string name, string token) { var regex = new System.Text.RegularExpressions.Regex(@"(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])"); return(regex.Replace(name, token)); }
/// <summary> /// バージョン情報の比較し、アップデートがあるか判定します。 /// </summary> /// <param name="clientVersion">クライアント側バージョン(1.2.3)</param> /// <param name="serverVersion">サーバ側バージョン(1.2.3)</param> /// <returns></returns> public static bool isNeedUpdate(string clientVersion, string serverVersion) { SimpleLogger.WriteLine("check update..."); if (clientVersion == null) { SimpleLogger.WriteLine("client version is null."); clientVersion = "0.0.0"; } if (serverVersion == null || serverVersion == "0.0.0") { SimpleLogger.WriteLine("failed to check version."); return(false); } System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^[0-9.]+$"); //if (clientVersion == "初実行") if (regex.IsMatch(clientVersion, 0) == false) { clientVersion = "0.0.0"; } string[] clv = clientVersion.Split('.'); string[] svv = serverVersion.Split('.'); int major_cl, major_sv, minor_cl, minor_sv, sub_cl, sub_sv; major_cl = System.Convert.ToInt32(clv[0]); minor_cl = System.Convert.ToInt32(clv[1]); sub_cl = System.Convert.ToInt32(clv[2]); major_sv = System.Convert.ToInt32(svv[0]); minor_sv = System.Convert.ToInt32(svv[1]); sub_sv = System.Convert.ToInt32(svv[2]); SimpleLogger.WriteLine("comparering version..."); if (clv.Length < 3 || svv.Length < 3) { SimpleLogger.WriteLine("failed to comparer version"); return(false); } SimpleLogger.WriteLine("Server: " + serverVersion); SimpleLogger.WriteLine("Client: " + clientVersion); // major version if (major_cl < major_sv) { SimpleLogger.WriteLine("need update."); return(true); } // minor version if (minor_cl < minor_sv) { SimpleLogger.WriteLine("need update."); return(true); } // sub version if (sub_cl < sub_sv) { SimpleLogger.WriteLine("need update."); return(true); } SimpleLogger.WriteLine("no update."); return(false); }
private bool IsNumberic(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"\d|\."); return(reg1.IsMatch(str)); }
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e) { var regex = new System.Text.RegularExpressions.Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); }
public void TestVariableParserV21() { var regex = new System.Text.RegularExpressions.Regex(Liquid.VariableParser); TestVariableParser((input) => DotLiquid.Util.R.Scan(input, regex)); }
private void btnSave_Click(object sender, RoutedEventArgs e) { try { System.Text.RegularExpressions.Regex regex = null; regex = new System.Text.RegularExpressions.Regex("^([a-zA-Z0-9])*$"); if (String.IsNullOrEmpty(txtPrjName.Text)) { MessageBox.Show("Invalid Project Name. Project Name cannot be empty."); return; } if (regex.IsMatch(txtPrjName.Text)) { XmlDocument xdoc = new XmlDocument(); xdoc.Load("New_Project_Template.xml"); foreach (XmlAttribute attr in xdoc.DocumentElement.Attributes) { if (attr.Name == "name") { attr.Value = txtPrjName.Text; } if (attr.Name == "project_baseline") { attr.Value = txtPrjBline.Text; } if (attr.Name == "uevol_baseline") { attr.Value = txtUevolBline.Text; } if (attr.Name == "sydb_version") { attr.Value = txtdbBline.Text; } if (attr.Name == "sydt_version") { attr.Value = txtSyDTVer.Text; } } SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "DTVT Blue Project (*.dtprj)|*.dtprj"; dlg.DefaultExt = ".dtprj"; dlg.ValidateNames = true; if (dlg.ShowDialog() == true) { newProjFilePath = dlg.FileName; xdoc.GetElementsByTagName("RootFolder")[0].Attributes["path"].Value = new System.IO.FileInfo(newProjFilePath).DirectoryName; xdoc.Save(dlg.FileName); } } else { MessageBox.Show("Invalid password. Password cannot contain any special characters."); return; } this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static bool ValidarNumeros(string valor) { System.Text.RegularExpressions.Regex oValidador = new System.Text.RegularExpressions.Regex("[0-9]"); return(oValidador.IsMatch(valor) || oValidador.IsMatch(valor)); }
bool ProcessKeyPressEvent(Gdk.EventKey ev) { // Short circuit to avoid getting moved back to the input line // when paging up and down in the shell output if (ev.Key == Gdk.Key.Page_Up || ev.Key == Gdk.Key.Page_Down) { return(false); } // Needed so people can copy and paste, but always end up // typing in the prompt. if (Cursor.Compare(InputLineBegin) < 0) { Buffer.MoveMark(Buffer.SelectionBound, InputLineEnd); Buffer.MoveMark(Buffer.InsertMark, InputLineEnd); } // if (ev.State == Gdk.ModifierType.ControlMask && ev.Key == Gdk.Key.space) // TriggerCodeCompletion (); if (ev.Key == Gdk.Key.Return) { if (inBlock) { if (InputLine == "") { ProcessInput(blockText); blockText = ""; inBlock = false; } else { blockText += "\n" + InputLine; string whiteSpace = null; if (auto_indent) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^(\s+).*"); whiteSpace = r.Replace(InputLine, "$1"); if (InputLine.EndsWith(BlockStart)) { whiteSpace += "\t"; } } Prompt(true, true); if (auto_indent) { InputLine += whiteSpace; } } } else { // Special case for start of new code block if (!string.IsNullOrEmpty(BlockStart) && InputLine.Trim().EndsWith(BlockStart)) { inBlock = true; blockText = InputLine; Prompt(true, true); if (auto_indent) { InputLine += "\t"; } return(true); } // Bookkeeping if (InputLine != "") { // Everything but the last item (which was input), //in the future stack needs to get put back into the // past stack while (commandHistoryFuture.Count > 1) { commandHistoryPast.Push(commandHistoryFuture.Pop()); } // Clear the pesky junk input line commandHistoryFuture.Clear(); // Record our input line commandHistoryPast.Push(InputLine); if (scriptLines == "") { scriptLines += InputLine; } else { scriptLines += "\n" + InputLine; } ProcessInput(InputLine); } } return(true); } // The next two cases handle command history else if (ev.Key == Gdk.Key.Up) { if (!inBlock && commandHistoryPast.Count > 0) { if (commandHistoryFuture.Count == 0) { commandHistoryFuture.Push(InputLine); } else { if (commandHistoryPast.Count == 1) { return(true); } commandHistoryFuture.Push(commandHistoryPast.Pop()); } InputLine = commandHistoryPast.Peek(); } return(true); } else if (ev.Key == Gdk.Key.Down) { if (!inBlock && commandHistoryFuture.Count > 0) { if (commandHistoryFuture.Count == 1) { InputLine = commandHistoryFuture.Pop(); } else { commandHistoryPast.Push(commandHistoryFuture.Pop()); InputLine = commandHistoryPast.Peek(); } } return(true); } else if (ev.Key == Gdk.Key.Left) { // Keep our cursor inside the prompt area if (Cursor.Compare(InputLineBegin) <= 0) { return(true); } } else if (ev.Key == Gdk.Key.Home) { Buffer.MoveMark(Buffer.InsertMark, InputLineBegin); // Move the selection mark too, if shift isn't held if ((ev.State & Gdk.ModifierType.ShiftMask) == ev.State) { Buffer.MoveMark(Buffer.SelectionBound, InputLineBegin); } return(true); } else if (ev.Key == Gdk.Key.period) { return(false); } // Short circuit to avoid getting moved back to the input line // when paging up and down in the shell output else if (ev.Key == Gdk.Key.Page_Up || ev.Key == Gdk.Key.Page_Down) { return(false); } return(false); }
private void SearchBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^[0-9]*$"); e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text)); }
public Object ObjectField(GUIContent label, Object obj, System.Type objType, bool allowSceneObjects) { #if UNITY_3_3 allowSceneObjects = true; #endif #if UNITY_3_3 obj = EditorGUILayout.ObjectField(label, obj, objType); #else obj = EditorGUILayout.ObjectField(label, obj, objType, allowSceneObjects); #endif if (obj != null) { if (allowSceneObjects && !EditorUtility.IsPersistent(obj)) { //Object is in the scene Component com = obj as Component; GameObject go = obj as GameObject; if (com != null) { go = com.gameObject; } if (go != null) { UnityReferenceHelper urh = go.GetComponent <UnityReferenceHelper> (); if (urh == null) { if (FixLabel("Object's GameObject must have a UnityReferenceHelper component attached")) { go.AddComponent <UnityReferenceHelper>(); } } } } else if (EditorUtility.IsPersistent(obj)) { string path = AssetDatabase.GetAssetPath(obj); System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"Resources[/|\\][^/]*$"); if (!rg.IsMatch(path)) { if (FixLabel("Object must be in the 'Resources' folder, top level")) { if (!System.IO.Directory.Exists(Application.dataPath + "/Resources")) { System.IO.Directory.CreateDirectory(Application.dataPath + "/Resources"); AssetDatabase.Refresh(); } string ext = System.IO.Path.GetExtension(path); string error = AssetDatabase.MoveAsset(path, "Assets/Resources/" + obj.name + ext); if (error == "") { //Debug.Log ("Successful move"); path = AssetDatabase.GetAssetPath(obj); } else { Debug.LogError("Couldn't move asset - " + error); } } } if (!AssetDatabase.IsMainAsset(obj) && obj.name != AssetDatabase.LoadMainAssetAtPath(path).name) { if (FixLabel("Due to technical reasons, the main asset must\nhave the same name as the referenced asset")) { string error = AssetDatabase.RenameAsset(path, obj.name); if (error == "") { //Debug.Log ("Successful"); } else { Debug.LogError("Couldn't rename asset - " + error); } } } } } return(obj); }
/// <summary>Determine index files that are no longer referenced /// and therefore should be deleted. This is called once /// (by the writer), and then subsequently we add onto /// deletable any files that are no longer needed at the /// point that we create the unused file (eg when merging /// segments), and we only remove from deletable when a /// file is successfully deleted. /// </summary> public void FindDeletableFiles() { // Gather all "current" segments: System.Collections.Hashtable current = new System.Collections.Hashtable(); for (int j = 0; j < segmentInfos.Count; j++) { SegmentInfo segmentInfo = (SegmentInfo)segmentInfos[j]; current[segmentInfo.name] = segmentInfo; } // Then go through all files in the Directory that are // Lucene index files, and add to deletable if they are // not referenced by the current segments info: System.String segmentsInfosFileName = segmentInfos.GetCurrentSegmentFileName(); IndexFileNameFilter filter = IndexFileNameFilter.GetFilter(); System.String[] files = directory.List(); for (int i = 0; i < files.Length; i++) { if (filter.Accept(null, files[i]) && !files[i].Equals(segmentsInfosFileName) && !files[i].Equals(IndexFileNames.SEGMENTS_GEN)) { System.String segmentName; System.String extension; // First remove any extension: int loc = files[i].IndexOf((System.Char) '.'); if (loc != -1) { extension = files[i].Substring(1 + loc); segmentName = files[i].Substring(0, (loc) - (0)); } else { extension = null; segmentName = files[i]; } // Then, remove any generation count: loc = segmentName.IndexOf((System.Char) '_', 1); if (loc != -1) { segmentName = segmentName.Substring(0, (loc) - (0)); } // Delete this file if it's not a "current" segment, // or, it is a single index file but there is now a // corresponding compound file: bool doDelete = false; if (!current.ContainsKey(segmentName)) { // Delete if segment is not referenced: doDelete = true; } else { // OK, segment is referenced, but file may still // be orphan'd: SegmentInfo info = (SegmentInfo)current[segmentName]; if (filter.IsCFSFile(files[i]) && info.GetUseCompoundFile()) { // This file is in fact stored in a CFS file for // this segment: doDelete = true; } else { Pattern p = new System.Text.RegularExpressions.Regex("s\\d+"); if ("del".Equals(extension)) { // This is a _segmentName_N.del file: if (!files[i].Equals(info.GetDelFileName())) { // If this is a seperate .del file, but it // doesn't match the current del filename for // this segment, then delete it: doDelete = true; } } else if (extension != null && extension.StartsWith("s") && p.Match(extension).Success) { int field = System.Int32.Parse(extension.Substring(1)); // This is a _segmentName_N.sX file: if (!files[i].Equals(info.GetNormFileName(field))) { // This is an orphan'd separate norms file: doDelete = true; } } else if ("cfs".Equals(extension) && !info.GetUseCompoundFile()) { // This is a partially written // _segmentName.cfs: doDelete = true; } } } if (doDelete) { AddDeletableFile(files[i]); if (infoStream != null) { infoStream.WriteLine("IndexFileDeleter: file \"" + files[i] + "\" is unreferenced in index and will be deleted on next commit"); } } } } }
/// <summary> /// 对主贴的回帖 /// </summary> /// <returns></returns> public ActionResult MakePostReply() { ////--------先把前端传回来的content内容保存为静态页面 byte[] byteData = new byte[Request.InputStream.Length]; //定义一个字节数组保存前端传回来的Post数据全部数据 Request.InputStream.Read(byteData, 0, byteData.Length); //将流读取到byteData,InputStream读取到的是http头里的主体数据 //string postData = System.Text.Encoding.Default.GetString(byteData);//系统的默认编码为gb2312,不适用这种 string postData = System.Text.Encoding.UTF8.GetString(byteData); postData = Server.UrlDecode(postData); //对数据进行url解码 string[] datas = postData.Split('&'); //对前端传回来的数据进行分割,提取出文本框里的html数据 string contentData = datas[0].ToString(); //data[0]为变量名为content的内容 contentData = contentData.Substring(contentData.IndexOf('=') + 1); //去除变量名,如content=aaa,只取出aaa DateTime datetime = DateTime.Now; string fileName = datetime.ToString("yyyyMMddHHmmss_ffff") + ".html"; //定义文件名fileName string fileNamePath = Server.MapPath("~/StaticHtml/HuiTieHtml/") + fileName; //物理路径 while (System.IO.File.Exists(fileNamePath)) //先判断文件是否存在,若存在:更换文件名 { datetime = DateTime.Now; fileName = datetime.ToString("yyyyMMddHHmmss_ffff") + ".html"; fileNamePath = Server.MapPath("~/StaticHtml/HuiTieHtml/") + fileName; } System.IO.FileStream fs = new System.IO.FileStream(fileNamePath, System.IO.FileMode.Create); byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(contentData); //byte[] contentBytes = System.Text.Encoding.Default.GetBytes(contentData); fs.Write(contentBytes, 0, contentBytes.Length); fs.Close();//---------保存静态html成功 ///----------/将数据保存到数据库里tb_ReplyPost (主贴编号 回帖者Id ///回帖内容的前200字符 点赞数 日期 回帖的静态html) int postId = Convert.ToInt32(Request["hidPostId"]); //主贴id int supportCount = 0; //点赞数 string replyUserName = Request["hidHuiTieUserName"].ToString(); User_bll user_bll = new User_bll(); int replyUserId = user_bll.GetUserId(replyUserName); //回帖者id string editorContent = datas[3].ToString(); //回帖内容的纯文本包含图片,data[3]的为前端传回来的发帖内容的纯文本 (备注:不能从request["editorContent"]读取,会报错提示说存在html标签) editorContent = editorContent.Substring(editorContent.IndexOf('=') + 1); System.Text.RegularExpressions.Regex regexImg = new System.Text.RegularExpressions.Regex(@"<img[^>]+>"); editorContent = regexImg.Replace(editorContent, "");//过滤掉editorContent里图片 int len = editorContent.Length; if (len > 200)//如果editorContent的长度超过200,取editorContent里的前两百个字符,将用于保存到数据库 { len = 200; } string content200 = editorContent.Substring(0, len); //回帖的200字符 string staticHuiTieHtml = "/StaticHtml/HuiTieHtml/" + fileName; //相对路径 ReplyPost_bll replyPost_bll = new ReplyPost_bll(); replyPost_bll.InsertReplyPost(postId, replyUserId, content200, supportCount, datetime, staticHuiTieHtml); //--------回帖数据保存成功 //////获取回帖里的所有图片的路径,并且将图片路径保存到数据库里tb_PostPhoto (PostPhoto_PostType=) System.Text.RegularExpressions.Regex regImg2 = new System.Text.RegularExpressions.Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);// 定义正则表达式用来匹配 img 标签 System.Text.RegularExpressions.MatchCollection matches = regImg2.Matches(contentData); int i = 0; string[] strUrlList = new string[matches.Count]; foreach (System.Text.RegularExpressions.Match match in matches) { strUrlList[i++] = match.Groups["imgUrl"].Value;// 取得匹配项列表 } if (strUrlList.Length >= 1) { int replyPostId = replyPost_bll.GetReplyPostId(staticHuiTieHtml);//根据回帖的静态html路径查询数据库,得到该贴子的replyPost_Id PostPhoto_bll postPhoto_bll = new PostPhoto_bll(); if (postPhoto_bll.InsertPhotoUrl(replyPostId, strUrlList, 2) < 0) { return(Content("保存图片路径时数据库出错")); } } return(Content("回帖成功")); }
protected internal System.Text.RegularExpressions.Match?Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, System.TimeSpan timeout) { throw null; }
public override TriggerSchemaCollection GetTableTriggers(TableSchema table) { if (table == null) { throw new ArgumentNullException("table"); } TriggerSchemaCollection triggers = new TriggerSchemaCollection(); using (IPooledDbConnection conn = connectionPool.Request()) { string sql = string.Format(@"SELECT Tables.Name TableName, Triggers.name TriggerName, Triggers.crdate TriggerCreatedDate, Comments.Text TriggerText FROM sysobjects Triggers INNER JOIN sysobjects Tables On Triggers.parent_obj = Tables.id INNER JOIN syscomments Comments On Triggers.id = Comments.id WHERE Triggers.xtype = 'TR' AND Tables.xtype = 'U' AND Tables.Name = '{0}' ORDER BY Tables.Name, Triggers.name" , table.Name); using (IDbCommand command = conn.CreateCommand(sql)) { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { System.Text.RegularExpressions.Regex parseRegEx = new System.Text.RegularExpressions.Regex (string.Concat( @"((CREATE\s*(Temp|Temporary)?\s*TRIGGER){1}\s?(\w+)\s?(IF NOT", @" EXISTS)?\s?(BEFORE|AFTER|INSTEAD OF){1}\s?(\w+)\s*ON(\s+\w*", @")\s*(FOR EACH ROW){1}\s*(BEGIN){1})\s+(\w|\W)*(END)")); TriggerSchema trigger = new TriggerSchema(this); trigger.TableName = table.Name; trigger.Name = r.GetString(r.GetOrdinal("TriggerName")); sql = r.GetString(r.GetOrdinal("TriggerText")); System.Text.RegularExpressions.MatchCollection matchs = parseRegEx.Matches(sql); if (matchs.Count > 0) { trigger.TriggerFireType = TriggerFireType.ForEachRow; switch (matchs[0].Groups[7].Value.ToLower()) { case "insert": trigger.TriggerEvent = TriggerEvent.Insert; break; case "update": trigger.TriggerEvent = TriggerEvent.Update; break; case "delete": trigger.TriggerEvent = TriggerEvent.Delete; break; default: throw new NotImplementedException(); } switch (matchs[0].Groups[7].Value.ToLower()) { case "before": trigger.TriggerType = TriggerType.Before; break; case "after": trigger.TriggerType = TriggerType.After; break; default: throw new NotImplementedException(); } StringBuilder sbSource = new StringBuilder(); foreach (System.Text.RegularExpressions.Capture c in matchs[0].Groups[11].Captures) { sbSource.Append(c.Value); } trigger.Source = sbSource.ToString(); } triggers.Add(trigger); } } } conn.Release(); } return(triggers); }
/// <summary>The entry form's keyboard keypress handler (except commandbar keypresses)</summary> void PanelLayout_KeyReleased(object sender, Xwt.KeyEventArgs e) { #if DEBUG pluginner.FileListPanel p1 = (PanelLayout.Panel1.Content as pluginner.FileListPanel); pluginner.FileListPanel p2 = (PanelLayout.Panel2.Content as pluginner.FileListPanel); Console.WriteLine("KEYBOARD DEBUG: " + e.Modifiers.ToString() + "+" + e.Key.ToString() + " was pressed. Panels focuses: " + (ActivePanel == p1) + " | " + (ActivePanel == p2)); #endif if (e.Key == Xwt.Key.Return) { return; //ENTER presses are handled by other event } string URL1; if (ActivePanel.ListingView.SelectedRow > -1) { URL1 = ActivePanel.GetValue(ActivePanel.dfURL); } else { URL1 = null; } pluginner.IFSPlugin FS1 = ActivePanel.FS; string URL2; if (PassivePanel.ListingView.SelectedRow > -1) { URL2 = PassivePanel.GetValue(PassivePanel.dfURL); } else { URL2 = null; } pluginner.IFSPlugin FS2 = PassivePanel.FS; switch (e.Key) { case Xwt.Key.NumPadAdd: //[+] gray - add selection string Filter = @"*.*"; InputBox ibx_qs = new InputBox(Locale.GetString("QuickSelect"), Filter); Xwt.CheckBox chkRegExp = new Xwt.CheckBox(Locale.GetString("NameFilterUseRegExp")); ibx_qs.OtherWidgets.Add(chkRegExp, 0, 0); if (!ibx_qs.ShowDialog()) { return; } Filter = ibx_qs.Result; if (chkRegExp.State == Xwt.CheckBoxState.Off) { Filter = Filter.Replace(".", @"\."); Filter = Filter.Replace("*", ".*"); Filter = Filter.Replace("?", "."); } try { System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(Filter); int Count = 0; foreach (pluginner.ListView2Item lvi in ActivePanel.ListingView.Items) { if (re.IsMatch(lvi.Data[1].ToString())) { ActivePanel.ListingView.Select(lvi); Count++; } } ActivePanel.StatusBar.Text = string.Format(Locale.GetString("NameFilterFound"), Filter, Count); } catch (Exception ex) { Xwt.MessageDialog.ShowError(Locale.GetString("NameFilterError"), ex.Message); } return; case Xwt.Key.NumPadSubtract: //[-] gray - add selection string Filter_qus = @"*.*"; InputBox ibx_qus = new InputBox(Locale.GetString("QuickUnselect"), Filter_qus); Xwt.CheckBox chkRegExp_qus = new Xwt.CheckBox(Locale.GetString("NameFilterUseRegExp")); ibx_qus.OtherWidgets.Add(chkRegExp_qus, 0, 0); if (!ibx_qus.ShowDialog()) { return; } Filter_qus = ibx_qus.Result; if (chkRegExp_qus.State == Xwt.CheckBoxState.Off) { Filter_qus = Filter_qus.Replace(".", @"\."); Filter_qus = Filter_qus.Replace("*", ".*"); Filter_qus = Filter_qus.Replace("?", "."); } try { System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(Filter_qus); int Count_qus = 0; foreach (pluginner.ListView2Item lvi in ActivePanel.ListingView.Items) { if (re.IsMatch(lvi.Data[1].ToString())) { ActivePanel.ListingView.Unselect(lvi); Count_qus++; } } } catch (Exception ex) { Xwt.MessageDialog.ShowError(Locale.GetString("NameFilterError"), ex.Message); } return; //F KEYS case Xwt.Key.F3: //F3: View. Shift+F3: View as text. if (URL1 == null) { return; } if (!FS1.FileExists(URL1)) { Xwt.MessageDialog.ShowWarning(string.Format(Locale.GetString("FileNotFound"), ActivePanel.GetValue(ActivePanel.dfDisplayName))); return; } VEd V = new VEd(); if (e.Modifiers == Xwt.ModifierKeys.None) { V.LoadFile(URL1, FS1, false); V.Show(); } else if (e.Modifiers == Xwt.ModifierKeys.Shift) { V.LoadFile(URL1, FS1, new base_plugins.ve.PlainText(), false); V.Show(); } //todo: handle Ctrl+F3 (Sort by name). return; case Xwt.Key.F4: //F4: Edit. Shift+F4: Edit as txt. if (URL1 == null) { return; } if (!FS1.FileExists(URL1)) { Xwt.MessageDialog.ShowWarning(string.Format(Locale.GetString("FileNotFound"), ActivePanel.GetValue(ActivePanel.dfDisplayName))); return; } VEd E = new VEd(); if (e.Modifiers == Xwt.ModifierKeys.None) { E.LoadFile(URL1, FS1, true); E.Show(); } else if (e.Modifiers == Xwt.ModifierKeys.Shift) { E.LoadFile(URL1, FS1, new base_plugins.ve.PlainText(), true); E.Show(); } //todo: handle Ctrl+F4 (Sort by extension). return; case Xwt.Key.F5: //F5: Copy. if (URL1 == null) { return; } Cp(); //todo: handle Ctrl+F5 (Sort by timestamp). return; case Xwt.Key.F6: //F6: Move/Rename. if (URL1 == null) { return; } Mv(); //todo: handle Ctrl+F6 (Sort by size). return; case Xwt.Key.F7: //F7: New directory. InputBox ibx = new InputBox(Locale.GetString("NewDirURL"), ActivePanel.FS.CurrentDirectory + Locale.GetString("NewDirTemplate")); if (ibx.ShowDialog()) { MkDir(ibx.Result); } return; case Xwt.Key.F8: //F8: delete if (URL1 == null) { return; } Rm(); //todo: move to trash can/recycle bin & handle Shit+F8 (remove completely) return; case Xwt.Key.F10: //F10: Exit //todo: ask user, are it really want to close FC? Xwt.Application.Exit(); //todo: handle Alt+F10 (directory tree) return; } #if DEBUG Console.WriteLine("KEYBOARD DEBUG: the key isn't handled"); #endif }
/// <summary> /// Returns a list of files in the index that match a regular expression. /// </summary> public List <string> GetFilesByRegex(System.Text.RegularExpressions.Regex pattern) { CheckPreload(); return(GetFilesByRegexImpl(pattern, m_configFiles)); }
/// <summary> /// Hàm này dùng để kiểm tra 1 string có phải là 1 số điện thoại ko? /// </summary> /// <param name="strphone"></param> /// <returns></returns> public static bool ValidatePhoneMask(string strphone) { System.Text.RegularExpressions.Regex regexObj = new System.Text.RegularExpressions.Regex(@"^([0-9]{3,5})?[ ]?([0-9]{3})[ ]?([0-9]{3})$"); return(regexObj.IsMatch(strphone)); }
public WebPermission(NetworkAccess access, System.Text.RegularExpressions.Regex uriRegex) { }
/// <summary> /// Gibt alle shows zurück bei denen titel oder beschreibung auf die suchanfrage passen /// </summary> /// <param name="query"></param> /// <returns></returns> public List <Show> getShowsBySearch(string query) { List <Show> result = new List <Show>(); List <Show> shows = getShows(); // Liste der einzelnen search queries List <string> splittedquery = query.Split(' ').ToList(); foreach (string request in splittedquery) { DateTime O_DATE; if (DateTime.TryParseExact(request, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out O_DATE)) { shows.ForEach(x => { Console.WriteLine(x.Datum.ToString("dd.MM.yyyy")); if (x.Datum.ToString("dd.MM.yyyy") == request) { if (result.FirstOrDefault(y => y.idShow == x.idShow) == null) { result.Add(x); } } }); continue; } // Postleizahl System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(@"^\d{5}$"); if (pattern.IsMatch(request)) { shows.ForEach(x => { if (x.Plz == request) { if (result.FirstOrDefault(y => y.idShow == x.idShow) == null) { result.Add(x); } } }); continue; } // Prüfe gegen rest shows.ForEach(x => { if (x.Titel.ToLower().Contains(request.Trim().ToLower()) || x.Beschreibung.ToLower().Contains(request.Trim().ToLower()) || x.Zusammenfassung.ToLower().Contains(request.Trim().ToLower()) || x.Ort.ToLower().Equals(request.Trim().ToLower()) || x.Strasse.ToLower().Equals(request.Trim().ToLower())) { if (result.FirstOrDefault(y => y.idShow == x.idShow) == null) { result.Add(x); } } }); } return(result); }
public bool IsNaturalNumber(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$"); return(reg1.IsMatch(str)); }
public static bool IsValidAddressRS(string address) { var regex = new System.Text.RegularExpressions.Regex( @"APL-[2-9A-HJ-NP-Z]{4}-[2-9A-HJ-NP-Z]{4}-[2-9A-HJ-NP-Z]{4}-[2-9A-HJ-NP-Z]{5}"); return regex.IsMatch(address) && address.Length == 24; }