private static void ChangeAgentDB() { if (File.Exists(".agent.db")) { var text = File.ReadAllText(".agent.db"); var evaluator1 = new MatchEvaluator(replaceAgent1); text = Regex.Replace( text, "(\"s2_)([A-Za-z]{4})(\")", evaluator1 ); text = Regex.Replace( text, "(http://)([A-Za-z]{4})(.patch.battle.net:1119/patch)", evaluator1 ); text = Regex.Replace( text, "(\"installed_locales\" : " + @"\[\s+" + "\")([A-Za-z]{4})(\")", evaluator1 ); text = Regex.Replace( text, "(\"display_locales\" : " + @"\[\s+" + "\")([A-Za-z]{4})(\")", evaluator1 ); File.Delete(".agent.db"); File.WriteAllText(".agent.db", text); } }
public static string Minify(System.Web.Mvc.UrlHelper urlHelper, string cssPath, string requestPath, string cssContent) { // this construct is to enable us to refer to the relativePath above ... MatchEvaluator urlDelegate = new MatchEvaluator(delegate(Match m) { // Change relative (to the original CSS) URL references to make them relative to the requested URL (controller / action) string url = m.Value; Uri uri = new Uri(url, UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri || VirtualPathUtility.IsAbsolute(url)) { // if the URL is absolute ("http://server/path/file.ext") or app absolute ("/path/file.ext") then leave it as it is } else { // get app relative url url = VirtualPathUtility.Combine(cssPath, url); url = VirtualPathUtility.MakeRelative(requestPath, url); url = urlHelper.Content(url); } return url; }); return Minify(urlHelper, urlDelegate, cssContent, 0); }
/// <summary> /// Replaces the characters null, alert, backspace, form feed, /// newline, carriage return, horizontal tab and vertical tab /// with their escaped version. This allows you to show /// the escape characters. /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ShowEscapeChars(string str) { Regex regex = new Regex("\0|\a|\b|\f|\n|\r|\t|\v"); MatchEvaluator evaluator = new MatchEvaluator((new StringUtil()).MatchEvent); return regex.Replace(str,evaluator); }
internal string Build (SubtitleCollection collection, SubtitleProperties subtitleProperties, FileProperties fileProperties) { this.subtitleProperties = subtitleProperties; StringBuilder output = new StringBuilder(); if (format.HasHeaders) output.Append(format.HeadersToString(subtitleProperties, fileProperties)); if (format.HasBodyBegin) output.Append(format.BodyBeginOut); string subtitleExpression = GetSubtitleExpression(format, subtitleProperties, fileProperties); Regex fieldExpression = new Regex(@"<<(?<Field>\w+)(,(?<Width>\d+))?>>"); MatchEvaluator matchEvaluator = new MatchEvaluator(this.FieldEvaluator); foreach (Subtitle currentSubtitle in collection) { subtitle = currentSubtitle; string outputSubtitle = fieldExpression.Replace(subtitleExpression, matchEvaluator); output.Append(outputSubtitle); output.Append("\n"); subtitleNumber++; previousSubtitle = subtitle; } if (format.HasBodyEnd) output.Append(format.BodyEndOut); subtitle = null; previousSubtitle = null; subtitleNumber = 1; ConvertNewlines(output, fileProperties); return output.ToString(); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(error); } HttpResponseBase response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonstring = serializer.Serialize(Data); string p = @"\\/Date\(\d+\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); Regex reg = new Regex(p); jsonstring = reg.Replace(jsonstring, matchEvaluator); response.Write(jsonstring); } }
/// <summary> /// 重写执行视图 /// </summary> /// <param name="context">上下文</param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (string.IsNullOrEmpty(this.ContentType)) { response.ContentType = this.ContentType; } else { response.ContentType = "application/json"; } if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data != null) { JavaScriptSerializer jss = new JavaScriptSerializer(); string jsonString = jss.Serialize(Data); string p = @"\\/Date\((\d+)\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString); Regex reg = new Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); response.Write(jsonString); } }
/// <summary> /// Expands links into HTML hyperlinks inside of text or HTML. /// </summary> /// <param name="text">The text to expand</param> /// <returns></returns> public string ExpandUrls(string text) { MatchEvaluator matchEval = null; string pattern = null; string updated = null; // *** Expand embedded hyperlinks RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase; if (ParseFormattedLinks) { pattern = @"\[(.*?)\|(.*?)]"; matchEval = new MatchEvaluator(ExpandFormattedLinks); updated = Regex.Replace(text, pattern, matchEval, options); } else updated = text; pattern = @"([""'=]|")?(http://|ftp://|https://|www\.|ftp\.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])"; matchEval = new MatchEvaluator(ExpandUrlsRegExEvaluator); updated = Regex.Replace(updated, pattern, matchEval, options); return updated; }
public string MinifyJavascript(string text) { // remove /* ... */ comments text = Regex.Replace(text, @"(?<!/)/\*((?!\*/).)*\*/", string.Empty, RegexOptions.Singleline); // remove // comments - remove all text beginning with // unless it is a hyperlink text = Regex.Replace(text, @"(?<!https?:)//[^\n\r]*[\n\r]", string.Empty, RegexOptions.IgnoreCase); //remove all line breaks and tabs text = Regex.Replace(text, @"[\f\n\r\t\v]", string.Empty, RegexOptions.Singleline); //remove all extraneous spaces text = Regex.Replace(text, @" {2,}", string.Empty); // temporarily replace spaces with a character sequence in the following: string phrases ("" or ''), regular expressions (//) var evaluator = new MatchEvaluator(ReplaceSpaces); text = Regex.Replace(text, @"'[^']*'|""[^""]*""", evaluator); // remove any spaces around code characters - excluded: / (because it is used for regular expressions) var codeCharacters = "[+*=(){}<>!|,;:?&-]+"; text = Regex.Replace(text, @"(?<!/) *(" + codeCharacters + ") *", "$1"); // restore spaces text = text.Replace("~¬@~", " "); return text; }
public static string DecodeNoTextileZones(string tmp, string patternPrefix, string patternSuffix, string[] exceptions) { m_decodeExceptions = exceptions; MatchEvaluator me = new MatchEvaluator(DecodeNoTextileZonesMatchEvaluator); tmp = Regex.Replace(tmp, string.Format("({0}(?<notex>.+?){1})*", patternPrefix, patternSuffix), me); return tmp; }
public static string ExpandUrls(string inputText) { string pattern = @"[""'=]?(http://|ftp://|https://|www\.|ftp\.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])"; System.Text.RegularExpressions.RegexOptions options = RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline | RegexOptions.IgnoreCase; System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern, options); MatchEvaluator MatchEval = new MatchEvaluator(ExpandUrlsRegExEvaluator); return Regex.Replace(inputText, pattern, MatchEval); }
/// <summary> /// 替换标签 /// </summary> /// <param name="html"></param> /// <param name="eval"></param> /// <returns></returns> public static string Replace(string html, MatchEvaluator eval) { //如果包含部分视图,则替换成部分视图的内容 //ReplacePartial(html); //替换匹配 return tagRegex.Replace(html, eval); }
public static string Fix(object data, MatchEvaluator replacer = null) { if (data == null) return null; string fixed_data; if (replacer != null) fixed_data = ControlChars.Value.Replace(data.ToString(), replacer); else fixed_data = ControlChars.Value.Replace(data.ToString(), FixData_Replace); return fixed_data; }
/// <summary> /// /// </summary> /// <param name="matchPattern"></param> /// <param name="source"></param> public static void ComplexReplace(string matchPattern, string source) { MatchEvaluator replaceCallback = new MatchEvaluator(MatchHandler); Regex RE = new Regex(matchPattern, RegexOptions.Multiline); string newString = RE.Replace(source, replaceCallback); Console.WriteLine("Replaced String = " + newString); }
// Replace some swf to mp4. public static void ChangeContent(ref string content, string pattern, MatchEvaluator evaluator) { Regex grx = new Regex(pattern, RegexOptions.IgnoreCase); if (grx.IsMatch(content)) { content = grx.Replace(content, evaluator); } }
public static string ConvertVariableLikeTOCInlines(string text, PreprocessedTextLocationMap map) { var evaluator = new MatchEvaluator(match => "[" + match.Groups["content"].Value + "]"); return map == null ? TOCPatternVariableLike.Replace(text, evaluator) : Preprocessor.Replace(TOCPatternVariableLike, text, evaluator, map); }
protected override string ReplaceNestedSequence(string templateText, string regExPattern, MatchEvaluator evaluator) { var result = templateText; Regex regEx = new Regex(regExPattern); while (regEx.IsMatch(result)) result = regEx.Replace(result, evaluator); return result; }
static string TagBasedConvertRegex(string input) { Regex r = new Regex("(<upcase>)(.+?)(</upcase>)"); MatchEvaluator eval = new MatchEvaluator(Replace); string result = r.Replace(input, eval); return result; }
/// <summary> /// A raw Html version of string.Format. This returns Html as text and /// not an HtmlString for easier manipulation. /// </summary> /// <param name="format">The format for the string this includes html</param> /// <param name="args"></param> /// <exception cref="FormatException">Thrown when the indexes in the format /// string are larger than the number of arguments passed.</exception> /// <returns></returns> public static string HtmlFormatRaw(this string format, params object[] args) { const string FormatSyntax = @"{(?<index>\d+)(?<rest>(?:,\-?\d+)?(?:\:\w+)?)}"; var func = new Func<object[], Match, string>(HtmlFormatter); var eval = new MatchEvaluator(func.Curry(args)); return Regex.Replace(format, FormatSyntax, eval); }
public string GetJsonString(object data) { var jsonString = JsonConvert.SerializeObject(data); //解码Unicode,也可以通过设置App.Config(Web.Config)设置来做,这里只是暂时弥补一下,用到的地方不多 MatchEvaluator evaluator = new MatchEvaluator(DecodeUnicode); var json = Regex.Replace(jsonString, @"\\u[0123456789abcdef]{4}", evaluator);//或:[\\u007f-\\uffff],\对应为\u000a,但一般情况下会保持\ return json; }
public String CreateClassName(String tableName) { MatchEvaluator UpCaser = new MatchEvaluator(UpCaserDef); tableName = Regex.Replace(tableName, "(tb_|_)", ""); tableName = Regex.Replace(tableName, "^[a-z]", UpCaser); return Singularize(tableName); }
public String CreateRelationName(String tableName) { MatchEvaluator UpCaser = new MatchEvaluator(UpCaserDef); tableName = Regex.Replace(tableName, "(tb_|_)", ""); tableName = Regex.Replace(tableName, "^[a-z]", UpCaser); return Pluralize(tableName); }
public string Format(string format, object[] values) { string regExpr = "\\{[0-9]+(:[a-zA-Z0-9#]+)?\\}"; this.values = values; Regex reg = new Regex(regExpr, RegexOptions.None); MatchEvaluator evelator = new MatchEvaluator(ApplayFormat); string tempres = reg.Replace(format, evelator); return tempres; }
/// <summary> /// 将数据实体序列化为Json字符串 /// </summary> /// <param name="data"></param> /// <returns></returns> public string GetJsonString(object data) { JavaScriptSerializer js = new JavaScriptSerializer(); var jsonString = js.Serialize(data); //解码Unicode,也可以通过设置App.Config(Web.Config)设置来做 MatchEvaluator evaluator = new MatchEvaluator(DecodeUnicode); var json = Regex.Replace(jsonString, @"\\u[0123456789abcdef]{4}", evaluator);//或:[\\u007f-\\uffff],\对应为\u000a,但一般情况下会保持\ return json; }
public LinkMapper(string path, string cpath, string format, string[] pages) { this.Linker = new PermalinkBuilder(path, format); this.Path = path; this.CommentPath = cpath; this.postmap = new Dictionary<string, Dictionary<string, List<string>>>(); this.Replacer = new MatchEvaluator(this.ResolveLink); foreach (string page in pages) this.AddPageToMap(page); }
private static string ReverseCapitalsAndInflatePalindromes(string currentLine) { Regex pattern = capitalWordsMatch; var capitalsAndPalindromesEvaluator = new MatchEvaluator(ReplaceCapitals); currentLine = pattern.Replace(currentLine, capitalsAndPalindromesEvaluator); return currentLine; }
/// <summary> /// Expands links into HTML hyperlinks inside of text or HTML. /// </summary> /// <param name="Text">The text to expand</param> /// <param name="Target">Target frame where output is displayed</param> /// <returns></returns> public string ExpandUrls(string Text) { // *** Expand embedded hyperlinks string regex = @"\b(((ftp|https?)://)?[-\w]+(\.\w[-\w]*)+|\w+\@|mailto:|[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)+(com\b|edu\b|biz\b|gov\b|in(?:t|fo)\b|mil\b|net\b|org\b|[a-z][a-z]\b)(:\d+)?(/[-a-z0-9_:\@&?=+,.!/~*'%\$]*)*(?<![.,?!])(?!((?!(?:<a )).)*?(?:</a>))(?!((?!(?:<!--)).)*?(?:-->))"; System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline) | System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options); MatchEvaluator MatchEval = new MatchEvaluator(this.ExpandUrlsRegExEvaluator); return Regex.Replace(Text, regex, MatchEval); }
public String CreatePropertyName(String columnName) { MatchEvaluator UpCaser = new MatchEvaluator(UpCaserDef); columnName = Regex.Replace(columnName, "([a-z])_([a-z])", UpCaser); columnName = Regex.Replace(columnName, "(tb_|_)", ""); columnName = Regex.Replace(columnName, "^[a-z]", UpCaser); columnName = Regex.Replace(columnName, "[^1-9a-zA-Z]", ""); return columnName; }
internal static string InnerModifyLine(string line) { // Replace "@...@" zones with "<code>" tags. MatchEvaluator me = new MatchEvaluator(CodeFormatMatchEvaluator); line = CodeBlockRegex.Replace(line, me); // Encode the contents of the "<code>" tags so that we don't // generate formatting out of it. line = NoTextileEncoder.EncodeNoTextileZones(line, @"(?<=(^|\s)<code(" + Globals.HtmlAttributesPattern + @")>)", @"(?=</code>)"); return line; }
internal AutoModeFilterStream(Stream stream, Encoding currentEncoding, bool processScripts, bool processStyles, bool combineCss, bool combineHeaderScripts) { _baseStream = stream; _currentEncoding = currentEncoding; _processScripts = processScripts; _processStyles = processStyles; _combineCss = combineCss; _combineHeaderScripts = combineHeaderScripts; _cssFiles = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); _headerScriptFiles = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); RemoveHeaderScriptMatchEvaluator = new MatchEvaluator(RemoveHeaderScript); RemoveCssMatchEvaluator = new MatchEvaluator(RemoveCss); }
public IEnumerable<string> Parse(string cssHackBody, Func<string, string> replaceUrl, out string replacedCssHackBody) { List<string> virtualPaths = new List<string>(); MatchEvaluator virtualPathEvaluator = new MatchEvaluator(delegate(Match m) { var virtualPath = m.Groups["VirualPath"].Value; virtualPaths.Add(virtualPath); return string.Format(@"href=""{0}""", replaceUrl(virtualPath)); }); replacedCssHackBody = regex.Replace(cssHackBody, virtualPathEvaluator); return virtualPaths; }
public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout) { return(new Regex(pattern, options, matchTimeout, true).Replace(input, evaluator)); }
public RegexReplace(string pattern, MatchEvaluator replacement, RegexOptions regexOptions) { _regex = new Regex(pattern, regexOptions); _replacementFunc = replacement; }
/// <summary> /// 替换模板数据 /// </summary> /// <param name="templateID"></param> /// <param name="eval"></param> /// <returns></returns> internal static string ReplaceTemplate(string templateID, MatchEvaluator eval) { string html = TemplateUtility.Read(templateID); return(TemplateRegexUtility.Replace(html, eval)); }
internal static string Replace(MatchEvaluator evaluator, Regex regex, string input, int count, int startat) { StringBuilder builder; if (evaluator == null) { throw new ArgumentNullException(); } if (count < -1) { throw new ArgumentOutOfRangeException(); } if ((startat < 0) || (startat > input.Length)) { throw new ArgumentOutOfRangeException(); } if (count == 0) { return(input); } Match match = regex.Match(input, startat); if (!match.Success) { return(input); } if (regex.RightToLeft) { ArrayList list = new ArrayList(); int length = input.Length; Label_00CE: if ((match.Index + match.Length) != length) { list.Add(input.Substring(match.Index + match.Length, (length - match.Index) - match.Length)); } length = match.Index; list.Add(evaluator(match)); if (--count != 0) { match = match.NextMatch(); if (match.Success) { goto Label_00CE; } } builder = new StringBuilder(); if (length > 0) { builder.Append(input, 0, length); } for (int i = list.Count - 1; i >= 0; i--) { builder.Append((string)list[i]); } goto Label_0177; } builder = new StringBuilder(); int startIndex = 0; Label_0051: if (match.Index != startIndex) { builder.Append(input, startIndex, match.Index - startIndex); } startIndex = match.Index + match.Length; builder.Append(evaluator(match)); if (--count != 0) { match = match.NextMatch(); if (match.Success) { goto Label_0051; } } if (startIndex < input.Length) { builder.Append(input, startIndex, input.Length - startIndex); } Label_0177: return(builder.ToString()); }
public static string Replace(string input, [StringSyntax(StringSyntaxAttribute.Regex, "options")] string pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout) => RegexCache.GetOrAdd(pattern, options, matchTimeout).Replace(input, evaluator);
public TemplateMapping(string template) { this.template = template; this.evaluator = new MatchEvaluator(SubstituteValue); }
public string Replace(string input, MatchEvaluator evaluator, int count, int startAt, RegexOptions options) => new Regex(this.Expression, options).Replace(input, evaluator, count, startAt);
/* * Replaces all ocurrances of the regex in the string with the * replacement evaluator. * * Note that the special case of no matches is handled on its own: * with no matches, the input string is returned unchanged. * The right-to-left case is split out because StringBuilder * doesn't handle right-to-left string building directly very well. */ internal static String Replace(MatchEvaluator evaluator, Regex regex, string input, int count, int startat) { Match match; if (evaluator == null) { throw new ArgumentNullException("evaluator"); } if (count < -1) { throw new ArgumentOutOfRangeException("count"); } if (startat < 0 || startat > input.Length) { throw new ArgumentOutOfRangeException("startat"); } if (count == 0) { return(input.ToString()); } match = regex.Match(input, startat); if (!match.Success) { return(input.ToString()); } else { StringBuilder sb; if (!regex.RightToLeft) { sb = new StringBuilder(); int prevat = 0; do { if (match.Index != prevat) { sb.Append(input.Substring(prevat, match.Index - prevat)); } prevat = match.Index + match.Length; sb.Append(evaluator(match)); if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) { sb.Append(input.Substring(prevat, input.Length - prevat)); } } else { List <String> al = new List <String>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) { al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); } prevat = match.Index; al.Add(evaluator(match)); if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); sb = new StringBuilder(); if (prevat > 0) { sb.Append(input.Substring(0, prevat)); } for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return(sb.ToString()); } }
public static string FixInvalidQuery(string query, string[] shortcuts, string[] operators = null) { if (operators == null) { operators = DefaultQueryOperators; } if (string.IsNullOrEmpty(query)) { return(query); } string newquery = query; //fix query ala (issues.issueTypeId:18+OR+issues.issueTypeId:12)+ico:00283924 if (!string.IsNullOrEmpty(query)) { query = query.Trim(); if (query.Contains("+") && !query.Contains(" ")) { newquery = System.Net.WebUtility.UrlDecode(query); } } MatchEvaluator evalDelimiterMatch = (m) => { var s = m.Value; if (string.IsNullOrEmpty(s)) { return(string.Empty); } if (m.Groups["v"].Success) { var v = m.Groups["v"]?.Value?.ToUpper()?.Trim() ?? ""; if (operators.Contains(v)) { return(s); } } var newVal = s.Replace(": ", ":"); return(newVal); }; foreach (var qo in shortcuts) { string lookFor = regexInvalidQueryTemplate.Replace("$operator$", qo); //if (modifiedQ.ToLower().Contains(lookFor.ToLower())) if (Regex.IsMatch(newquery, lookFor, regexQueryOption)) { newquery = Regex.Replace(newquery, lookFor, evalDelimiterMatch, regexQueryOption); } } // [\p{L}\p{M}\d_] \p{L} -znaky všech abeced \p{M} -kombinované znaky string invalidFormatRegex = @"(AND \s+)? ([^""]\w +\.?\w +) :($|[^\""=><[\p{L}\p{M}\d_{)]) (AND )?"; Match mIsInvalid = Regex.Match(query, invalidFormatRegex, (RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase)); if (mIsInvalid.Success) { newquery = Regex.Replace(newquery, invalidFormatRegex, " ", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase).Trim(); } var textParts = Devmasters.TextUtil.SplitStringToPartsWithQuotes(newquery, '\"'); //make operator UpperCase and space around '(' and ')' if (textParts.Count > 0) { string fixedOperator = ""; foreach (var tp in textParts) { if (tp.Item2 == true) { fixedOperator = fixedOperator + tp.Item1; } else { var fixPart = tp.Item1; fixPart = System.Net.WebUtility.UrlDecode(fixPart); fixPart = System.Net.WebUtility.HtmlDecode(fixPart); Regex opReg = new Regex(string.Format(@"(^|\s)({0})(\s|$)", operators.Aggregate((f, s) => f + "|" + s)), regexQueryOption); //UPPER Operator fixPart = opReg.Replace(fixPart, (me) => { return(me.Value.ToUpper()); }); //Space around '(' and ')' fixPart = fixPart.Replace("(", "( ").Replace(")", " )"); fixedOperator = fixedOperator + fixPart; } } newquery = fixedOperator; } //fix DÚK/Sou/059/2009 -> DÚK\\/Sou\\/059\\/2009 // // but support regex name:/joh?n(ath[oa]n)/ // //if (newquery.Contains("/")) //&& regFindRegex.Match(query).Success == false) //{ // newquery = newquery.Replace("/", "\\/"); //} //fix with small "to" in zverejneno:[2018-12-13 to *] var dateintervalRegex = @"(podepsano|zverejneno):({|\[)\d{4}\-\d{2}\-\d{2}(?<to> \s*to\s*)(\d{4}-\d{2}-\d{2}|\*)(}|\])"; if (Regex.IsMatch(newquery, dateintervalRegex, regexQueryOption)) { newquery = newquery.ReplaceGroupMatchNameWithRegex(dateintervalRegex, "to", " TO "); } if (newquery != query) { return(newquery); } else { return(query); } }
private static string GetSimpleQueryCore <T>(string query, Rule[] rules) where T : class { query = query?.Trim(); if (query == null) { return(null); } else if (string.IsNullOrEmpty(query) || query == "*") { return(""); } string regexPrefix = @"(^|\s|[(])"; string regexTemplate = "{0}(?<q>(-|\\w)*)\\s*"; string modifiedQ = query; //FixInvalidQuery(query) ?? ""; //check invalid query ( tag: missing value) for (int i = 0; i < rules.Length; i++) { string lookFor = regexPrefix + rules[i].LookFor; string replaceWith = rules[i].ReplaceWith; bool doFullReplace = rules[i].FullReplace; MatchEvaluator evalMatch = (m) => { var s = m.Value; if (string.IsNullOrEmpty(s)) { return(string.Empty); } var newVal = replaceWith; if (newVal.Contains("${q}")) { var capt = m.Groups["q"].Captures; var captVal = ""; foreach (Capture c in capt) { if (c.Value.Length > captVal.Length) { captVal = c.Value; } } newVal = newVal.Replace("${q}", captVal); } if (s.StartsWith("(")) { return(" (" + newVal); } else { return(" " + newVal); } }; //if (modifiedQ.ToLower().Contains(lookFor.ToLower())) if (Regex.IsMatch(modifiedQ, lookFor, regexQueryOption)) { Match mFirst = Regex.Match(modifiedQ, lookFor, regexQueryOption); string foundValue = mFirst.Groups["q"].Value; if (doFullReplace && !string.IsNullOrEmpty(replaceWith) && ( lookFor.Contains("holding:") //RS || lookFor.Contains("holdingprijemce:") || lookFor.Contains("holdingplatce:") //insolvence || lookFor.Contains("holdingdluznik:") || lookFor.Contains("holdingveritel:") || lookFor.Contains("holdingspravce:") //VZ || lookFor.Contains("holdingdodavatel:") || lookFor.Contains("holdingzadavatel:") ) ) { //list of ICO connected to this holding Match m = Regex.Match(modifiedQ, lookFor, regexQueryOption); string holdingIco = m.Groups["q"].Value; HlidacStatu.Lib.Data.Relation.AktualnostType aktualnost = HlidacStatu.Lib.Data.Relation.AktualnostType.Nedavny; Data.Firma f = Data.Firmy.Get(holdingIco); if (f != null && f.Valid) { var icos = new string[] { f.ICO } .Union( f.AktualniVazby(aktualnost) .Select(s => s.To.Id) ) .Distinct(); string icosQuery = ""; var icosPresLidi = f.AktualniVazby(aktualnost) .Where(o => o.To.Type == Data.Graph.Node.NodeType.Person) .Select(o => Data.Osoby.GetById.Get(Convert.ToInt32(o.To.Id))) .Where(o => o != null) .SelectMany(o => o.AktualniVazby(aktualnost)) .Select(v => v.To.Id) .Distinct(); icos = icos.Union(icosPresLidi).Distinct(); var templ = $" ( {replaceWith}:{{0}} ) "; if (replaceWith.Contains("${q}")) { templ = $" ( {replaceWith.Replace("${q}", "{0}")} )"; } if (icos != null && icos.Count() > 0) { icosQuery = " ( " + icos .Select(t => string.Format(templ, t)) .Aggregate((fi, s) => fi + " OR " + s) + " ) "; } else { icosQuery = string.Format(templ, "noOne"); //$" ( {icoprefix}:noOne ) "; } if (!string.IsNullOrEmpty(rules[i].AddLastCondition)) { if (rules[i].AddLastCondition.Contains("${q}")) { rules[i].AddLastCondition = rules[i].AddLastCondition.Replace("${q}", foundValue); } icosQuery = Query.ModifyQueryOR(icosQuery, rules[i].AddLastCondition); rules[i].AddLastCondition = null; //done, don't do it anywhere } modifiedQ = Regex.Replace(modifiedQ, lookFor, " (" + icosQuery + ") ", regexQueryOption); } } //do regex replace else if (doFullReplace && !string.IsNullOrEmpty(replaceWith) && ( lookFor.Contains("osobaid:") || lookFor.Contains("osobaiddluznik:") || lookFor.Contains("osobaidveritel:") || lookFor.Contains("osobaidspravce:") || lookFor.Contains("osobaidzadavatel:") || lookFor.Contains("osobaiddodavatel:") ) )//(replaceWith.Contains("${ico}")) { //list of ICO connected to this person Match m = Regex.Match(modifiedQ, lookFor, regexQueryOption); string nameId = m.Groups["q"].Value; Data.Osoba p = Data.Osoby.GetByNameId.Get(nameId); string icosQuery = ""; //string icoprefix = replaceWith; var templ = $" ( {replaceWith}:{{0}} ) "; if (replaceWith.Contains("${q}")) { templ = $" ( {replaceWith.Replace("${q}", "{0}")} )"; } if (p != null) { var icos = p .AktualniVazby(Data.Relation.AktualnostType.Nedavny) .Where(w => !string.IsNullOrEmpty(w.To.Id)) //.Where(w => Analysis.ACore.GetBasicStatisticForICO(w.To.Id).Summary.Pocet > 0) .Select(w => w.To.Id) .Distinct().ToArray(); if (icos != null && icos.Length > 0) { icosQuery = " ( " + icos .Select(t => string.Format(templ, t)) .Aggregate((f, s) => f + " OR " + s) + " ) "; } else { icosQuery = string.Format(templ, "noOne"); //$" ( {icoprefix}:noOne ) "; } if (!string.IsNullOrEmpty(rules[i].AddLastCondition)) { if (rules[i].AddLastCondition.Contains("${q}")) { rules[i].AddLastCondition = rules[i].AddLastCondition.Replace("${q}", foundValue); } icosQuery = Query.ModifyQueryOR(icosQuery, rules[i].AddLastCondition); rules[i].AddLastCondition = null; //done, don't do it anywhere } modifiedQ = Regex.Replace(modifiedQ, lookFor, " (" + icosQuery + ") ", regexQueryOption); } else { modifiedQ = Regex.Replace(modifiedQ, lookFor, " (" + string.Format(templ, "noOne") + ") ", regexQueryOption); } } //VZ else if (doFullReplace && replaceWith.Contains("${oblast}")) { if (replaceWith.Contains("${oblast}")) { var oblastVal = Devmasters.RegexUtil.GetRegexGroupValue(modifiedQ, @"oblast:(?<oblast>\w*)", "oblast"); var cpvs = Lib.Data.VZ.VerejnaZakazka.Searching.CPVOblastToCPV(oblastVal); if (cpvs != null) { var q_cpv = "cPV:(" + cpvs.Select(s => s + "*").Aggregate((f, s) => f + " OR " + s) + ")"; modifiedQ = Regex.Replace(modifiedQ, @"oblast:(?<oblast>\w*)", q_cpv, regexQueryOption); } } } //VZs else if (doFullReplace && replaceWith.Contains("${cpv}")) { string cpv = ""; //Match m = Regex.Match(modifiedQ, lookFor, regexQueryOption); //string cpv = ""; //if (m.Success) // cpv = m.Groups["q"].Value; cpv = Devmasters.RegexUtil.GetRegexGroupValue(modifiedQ, @"cpv:(?<q>(-|,|\d)*)\s*", "q"); lookFor = @"cpv:(?<q>(-|,|\d)*)\s*"; if (!string.IsNullOrEmpty(cpv)) { string[] cpvs = cpv.Split(new char[] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries); string q_cpv = ""; if (cpvs.Length > 0) { q_cpv = "cPV:(" + cpvs.Select(s => s + "*").Aggregate((f, s) => f + " OR " + s) + ")"; } modifiedQ = Regex.Replace(modifiedQ, lookFor, " (" + q_cpv + ") ", regexQueryOption); } else { modifiedQ = Regex.Replace(modifiedQ, lookFor, " ", regexQueryOption); } } //VZ else if (doFullReplace && replaceWith.Contains("${form}")) { lookFor = @"form:(?<q>((F|CZ)\d{1,2}(,)?)*)\s*"; Match m = Regex.Match(modifiedQ, lookFor, regexQueryOption); string form = ""; if (m.Success) { form = m.Groups["q"].Value; } if (!string.IsNullOrEmpty(form)) { string[] forms = form.Split(new char[] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries); string q_form = ""; if (forms.Length > 0) { q_form = "formulare.druh:(" + forms.Select(s => s + "*").Aggregate((f, s) => f + " OR " + s) + ")"; } modifiedQ = Regex.Replace(modifiedQ, lookFor, " (" + q_form + ") ", regexQueryOption); } else { modifiedQ = Regex.Replace(modifiedQ, lookFor, " ", regexQueryOption); } } else if (replaceWith.Contains("${q}")) { modifiedQ = Regex.Replace(modifiedQ, string.Format(regexTemplate, lookFor), evalMatch, regexQueryOption); } //do regex replace else if (doFullReplace && lookFor.Contains("chyby:")) { string levelVal = Devmasters.RegexUtil.GetRegexGroupValue(modifiedQ, @"chyby:(?<level>\w*)", "level")?.ToLower() ?? ""; string levelQ = ""; if (levelVal == "fatal" || levelVal == "zasadni") { levelQ = Lib.Issues.Util.IssuesByLevelQuery(Lib.Issues.ImportanceLevel.Fatal); } else if (levelVal == "major" || levelVal == "vazne") { levelQ = Lib.Issues.Util.IssuesByLevelQuery(Lib.Issues.ImportanceLevel.Major); } if (!string.IsNullOrEmpty(levelQ)) { modifiedQ = Regex.Replace(modifiedQ, @"chyby:(\w*)", levelQ, regexQueryOption); } } else if (!string.IsNullOrEmpty(replaceWith)) { modifiedQ = Regex.Replace(modifiedQ, lookFor, evalMatch, regexQueryOption); } if (!string.IsNullOrEmpty(rules[i].AddLastCondition)) { if (rules[i].AddLastCondition.Contains("${q}")) { rules[i].AddLastCondition = rules[i].AddLastCondition.Replace("${q}", foundValue); } modifiedQ = Query.ModifyQueryOR(modifiedQ, rules[i].AddLastCondition); } } } return(modifiedQ); }
/// <summary> /// Replaces all occurrences of the regex in the string with the /// replacement evaluator. /// /// Note that the special case of no matches is handled on its own: /// with no matches, the input string is returned unchanged. /// The right-to-left case is split out because StringBuilder /// doesn't handle right-to-left string building directly very well. /// </summary> internal static string Replace(MatchEvaluator evaluator, Regex regex, string input, int count, int startat, ref long replacements) { if (evaluator == null) { throw new ArgumentNullException(nameof(evaluator)); } if (count < -1) { throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall); } if (startat < 0 || startat > input.Length) { throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative); } if (count == 0) { return(input); } Match match = regex.Match(input, startat); if (!match.Success) { return(input); } else { Span <char> charInitSpan = stackalloc char[ReplaceBufferSize]; var vsb = new ValueStringBuilder(charInitSpan); if (!regex.RightToLeft) { int prevat = 0; do { if (match.Index != prevat) { vsb.Append(input.AsSpan(prevat, match.Index - prevat)); } prevat = match.Index + match.Length; string result = evaluator(match); if (!string.IsNullOrEmpty(result)) { vsb.Append(result); } ++replacements; if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) { vsb.Append(input.AsSpan(prevat, input.Length - prevat)); } } else { // In right to left mode append all the inputs in reversed order to avoid an extra dynamic data structure // and to be able to work with Spans. A final reverse of the transformed reversed input string generates // the desired output. Similar to Tower of Hanoi. int prevat = input.Length; do { if (match.Index + match.Length != prevat) { vsb.AppendReversed(input.AsSpan(match.Index + match.Length, prevat - match.Index - match.Length)); } prevat = match.Index; vsb.AppendReversed(evaluator(match).AsSpan()); ++replacements; if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); if (prevat > 0) { vsb.AppendReversed(input.AsSpan(0, prevat)); } vsb.Reverse(); } return(vsb.ToString()); } }
public string Replace(string input, MatchEvaluator evaluator) => Regex.Replace(input, this.Expression, evaluator, RegexOptions.Multiline);
private string EvalTextContainsExpression(string exp) { var evalutor = new MatchEvaluator(m => EvalExpression(m.Value).ToString()); return(expressionRecognizeRegex.Replace(exp, evalutor)); }
public string Replace(string input, MatchEvaluator evaluator, int count, RegexOptions options, TimeSpan matchTimeout) => new Regex(this.Expression, options, matchTimeout).Replace(input, evaluator, count);
/// <summary> /// Adds a rule for transforming CSS to XPath. /// </summary> /// <param name="regex">A Regex for the parts of the CSS you want to transform.</param> /// <param name="replacement">A MatchEvaluator for converting the matched CSS parts to XPath.</param> /// <exception cref="ArgumentException">Thrown if regex or replacement is null.</exception> /// <example> /// <code> /// // Handle :contains selectors /// AddRule(new Regex(@":contains\(([^\)]*)\)"), new MatchEvaluator((Match m) => { /// return "[contains(string(.),'" + m.Groups[1].Value + "')]"; /// })); /// /// // Note: Remember that m.Groups[1] refers to the first captured group; m.Groups[0] refers /// // to the entire match. /// </code> /// </example> public static void AddRule(Regex regex, MatchEvaluator replacement) { _AddRule(regex, replacement); }
/// <summary> /// Perform a substring replace using a regular expression. /// </summary> /// /// <param name="input"> /// The target of the replacement. /// </param> /// <param name="pattern"> /// The pattern to match. /// </param> /// <param name="evaluator"> /// The evaluator. /// </param> /// /// <returns> /// A new string. /// </returns> public static string RegexReplace(this String input, string pattern, MatchEvaluator evaluator) { return(Regex.Replace(input, pattern, evaluator)); }
public string Replace(string input, MatchEvaluator evaluator, int count) => new Regex(this.Expression, RegexOptions.Multiline).Replace(input, evaluator, count);
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { //1 Gosper curve construction //1.1 Generate character encoding int iterateNum = 3; //Set the number of iterations string codeString = "A"; //Initial encoding //Iterative replacement of encoding by regular expression string replace = "A|B"; Regex regex = new Regex(replace); MatchEvaluator matchEvaluator = new MatchEvaluator(Rules); //Complete the specified number of iterations for (int i = 0; i < iterateNum; i++) { codeString = regex.Replace(codeString, matchEvaluator); } ///1.2 Generate Gosper curves according to character encoding //Start point setting GosperX = oriX; GosperY = oriY; IPoint oriPt = new PointClass(); oriPt.X = GosperX; oriPt.Y = GosperY; //Add start point to node set curvePtCol = new PolylineClass(); curvePtCol.AddPoint(oriPt); //Translate character encoding and draw according to its meaning for (int i = 0; i < codeString.Length; i++) { string order = codeString[i].ToString(); switch (order) { case "A": case "B": GenerateGosperNode(forwardAngle); break; case "-": forwardAngle -= Math.PI / 3; //Turn 60 degrees counter clockwise break; case "+": forwardAngle += Math.PI / 3; //Turn 60 degrees clockwise break; } } //2 Output the generated Gosper curve //Output address settings string gdbPath = @"FilePath\FileName.gdb"; string GosperLineName = "GosperLine";//Set the output name CommonTool commonTool = new CommonTool(gdbPath); //Output the result GosperLine = curvePtCol as IPolyline; IFeatureClass gosperLineFeaClass = commonTool.CreateFeatureClassWithoutAttribute(GosperLineName, esriGeometryType.esriGeometryPolyline); IFeature lineFea = gosperLineFeaClass.CreateFeature(); lineFea.Shape = GosperLine; lineFea.Store(); MessageBox.Show("OK"); }
public static string ReplaceMatches(this string source, MatchCollection matches, MatchEvaluator evaluator) { var sb = new StringBuilder(source.Length); var prevPos = 0; foreach (var match in matches.Cast <Match>()) { sb.Append(source, prevPos, match.Index - prevPos); prevPos = match.Index + match.Length; var replacement = evaluator(match); sb.Append(replacement); } sb.Append(source, prevPos, source.Length - prevPos); return(sb.ToString()); }
public string Replace(string input, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout) => Regex.Replace(input, this.Expression, evaluator, options, matchTimeout);
/// <summary> /// Replaces all occurrences of the <paramref name="pattern"/> with the recent /// replacement pattern. /// </summary> public static string Replace(string input, [StringSyntax(StringSyntaxAttribute.Regex)] string pattern, MatchEvaluator evaluator) => RegexCache.GetOrAdd(pattern).Replace(input, evaluator);
public static string Apply(this string str, Regex expression, MatchEvaluator evaluator) { return(expression.Replace(str, evaluator)); }
/// <summary> /// 设置属性值 /// </summary> /// <param name="element">要设置属性的元素</param> /// <param name="attributeName">属性名</param> /// <param name="pattern">用于在属性值中查找匹配字符串的正则表达式对象</param> /// <param name="evaluator">替换字符串</param> /// <returns></returns> public static IHtmlElement SetAttribute(this IHtmlElement element, string attributeName, Regex pattern, MatchEvaluator evaluator) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeName == null) { throw new ArgumentNullException("attributeName"); } if (pattern == null) { throw new ArgumentNullException("pattern"); } return(SetAttribute(element, attributeName, value => pattern.Replace(value, evaluator))); }
public static string Minify(System.Web.Mvc.UrlHelper urlHelper, MatchEvaluator urlReplacer, string cssContent, int columnWidth) { // BSD License http://developer.yahoo.net/yui/license.txt // New css tests and regexes by Michael Ash MatchEvaluator rgbDelegate = new MatchEvaluator(RGBMatchHandler); MatchEvaluator shortColorNameDelegate = new MatchEvaluator(ShortColorNameMatchHandler); MatchEvaluator shortColorHexDelegate = new MatchEvaluator(ShortColorHexMatchHandler); cssContent = RemoveCommentBlocks(cssContent); cssContent = Regex.Replace(cssContent, @"\s+", " "); //Normalize whitespace cssContent = Regex.Replace(cssContent, @"\x22\x5C\x22}\x5C\\x22\x22", "___PSEUDOCLASSBMH___"); //hide Box model hack /* Remove the spaces before the things that should not have spaces before them. * But, be careful not to turn "p :link {...}" into "p:link{...}" */ cssContent = Regex.Replace(cssContent, @"(?#no preceding space needed)\s+((?:[!{};>+()\],])|(?<={[^{}]*):(?=[^}]*}))", "$1"); cssContent = Regex.Replace(cssContent, @"([!{}:;>+([,])\s+", "$1"); // Remove the spaces after the things that should not have spaces after them. cssContent = Regex.Replace(cssContent, @"([^;}])}", "$1;}"); // Add the semicolon where it's missing. cssContent = Regex.Replace(cssContent, @"(\d+)\.0+(p(?:[xct])|(?:[cem])m|%|in|ex)\b", "$1$2"); // Remove .0 from size units x.0em becomes xem cssContent = Regex.Replace(cssContent, @"([\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)\b", "$1$2"); // Remove unit from zero //New test //Font weights cssContent = Regex.Replace(cssContent, @"(?<=font-weight:)normal\b", "400"); cssContent = Regex.Replace(cssContent, @"(?<=font-weight:)bold\b", "700"); //Thought this was a good idea but properties of a set not defined get element defaults. This is reseting them. css = ShortHandProperty(css); cssContent = ShortHandAllProperties(cssContent); //css = Regex.Replace(css, @":(\s*0){2,4}\s*;", ":0;"); // if all parameters zero just use 1 parameter // if all 4 parameters the same unit make 1 parameter //css = Regex.Replace(css, @":\s*(inherit|auto|0|(?:(?:\d*\.?\d+(?:p(?:[xct])|(?:[cem])m|%|in|ex))))(\s+\1){1,3};", ":$1;", RegexOptions.IgnoreCase); //if background-position:500px 500px; replaced to background-position:500px;, that will parsed to background-position:500px 50% at the client. // if has 4 parameters and top unit = bottom unit and right unit = left unit make 2 parameters cssContent = Regex.Replace(cssContent, @":\s*((inherit|auto|0|(?:(?:\d*\.?\d+(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+(inherit|auto|0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex)))))\s+\2\s+\3;", ":$1;", RegexOptions.IgnoreCase); // if has 4 parameters and top unit != bottom unit and right unit = left unit make 3 parameters cssContent = Regex.Replace(cssContent, @":\s*((?:(?:inherit|auto|0|(?:(?:\d*\.?\d+(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+)?(inherit|auto|0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+(?:0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex)))))\s+\2;", ":$1;", RegexOptions.IgnoreCase); //// if has 3 parameters and top unit = bottom unit make 2 parameters //css = Regex.Replace(css, @":\s*((0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex))))\s+(?:0|(?:(?:\d?\.?\d(?:p(?:[xct])|(?:[cem])m|%|in|ex)))))\s+\2;", ":$1;", RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, "background-position:0;", "background-position:0 0;"); cssContent = Regex.Replace(cssContent, @"(:|\s)0+\.(\d+)", "$1.$2"); // Outline-styles and Border-sytles parameter reduction cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*(none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)(?:\s+\2){1,3};", "$1-style:$2;", RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*((none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)\s+(none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset ))(?:\s+\3)(?:\s+\4);", "$1-style:$2;", RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*((?:(?:none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)\s+)?(none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset )\s+(?:none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset ))(?:\s+\3);", "$1-style:$2;", RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(outline|border)-style\s*:\s*((none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset)\s+(?:none|hidden|d(?:otted|ashed|ouble)|solid|groove|ridge|inset|outset ))(?:\s+\3);", "$1-style:$2;", RegexOptions.IgnoreCase); // Outline-color and Border-color parameter reduction cssContent = Regex.Replace(cssContent, @"(outline|border)-color\s*:\s*((?:\#(?:[0-9A-F]{3}){1,2})|\S+)(?:\s+\2){1,3};", "$1-color:$2;", RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(outline|border)-color\s*:\s*(((?:\#(?:[0-9A-F]{3}){1,2})|\S+)\s+((?:\#(?:[0-9A-F]{3}){1,2})|\S+))(?:\s+\3)(?:\s+\4);", "$1-color:$2;", RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(outline|border)-color\s*:\s*((?:(?:(?:\#(?:[0-9A-F]{3}){1,2})|\S+)\s+)?((?:\#(?:[0-9A-F]{3}){1,2})|\S+)\s+(?:(?:\#(?:[0-9A-F]{3}){1,2})|\S+))(?:\s+\3);", "$1-color:$2;", RegexOptions.IgnoreCase); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. cssContent = Regex.Replace(cssContent, @"rgb\s*\x28((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*,\s*((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*,\s*((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*\x29", rgbDelegate); cssContent = Regex.Replace(cssContent, @"(?<![\x22\x27=]\s*)\#(?:([0-9A-F])\1)(?:([0-9A-F])\2)(?:([0-9A-F])\3)", "#$1$2$3", RegexOptions.IgnoreCase); // Replace hex color code with named value is shorter cssContent = Regex.Replace(cssContent, @"(?<=color\s*:\s*.*)\#(?<hex>f00)\b", "red", RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(?<=color\s*:\s*.*)\#(?<hex>[0-9a-f]{6})", shortColorNameDelegate, RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(?<=color\s*:\s*)\b(Black|Fuchsia|LightSlateGr[ae]y|Magenta|White|Yellow)\b", shortColorHexDelegate, RegexOptions.IgnoreCase); // replace URLs if (urlReplacer != null) { cssContent = Regex.Replace(cssContent, @"(?<=url\(\s*([""']?))(?<url>[^'""]+?)(?=\1\s*\))", urlReplacer, RegexOptions.IgnoreCase); cssContent = Regex.Replace(cssContent, @"(?<=@import\s*([""']))(?<url>[^'""]+?)(?=\1\s*;)", urlReplacer, RegexOptions.IgnoreCase); } // Remove empty rules. cssContent = Regex.Replace(cssContent, @"[^}]+{;}", ""); //Remove semicolon of last property cssContent = Regex.Replace(cssContent, ";(})", "$1"); if (columnWidth > 0) { cssContent = BreakLines(cssContent, columnWidth); } return(cssContent); }
/// <summary> /// Replaces all occurrences of the regex in the string with the /// replacement evaluator. /// /// Note that the special case of no matches is handled on its own: /// with no matches, the input string is returned unchanged. /// The right-to-left case is split out because StringBuilder /// doesn't handle right-to-left string building directly very well. /// </summary> internal static String Replace(MatchEvaluator evaluator, Regex regex, String input, int count, int startat) { if (evaluator == null) { throw new ArgumentNullException(nameof(evaluator)); } if (count < -1) { throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall); } if (startat < 0 || startat > input.Length) { throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative); } if (count == 0) { return(input); } Match match = regex.Match(input, startat); if (!match.Success) { return(input); } else { StringBuilder sb = StringBuilderCache.Acquire(); if (!regex.RightToLeft) { int prevat = 0; do { if (match.Index != prevat) { sb.Append(input, prevat, match.Index - prevat); } prevat = match.Index + match.Length; sb.Append(evaluator(match)); if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) { sb.Append(input, prevat, input.Length - prevat); } } else { List <String> al = new List <String>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) { al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); } prevat = match.Index; al.Add(evaluator(match)); if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); if (prevat > 0) { sb.Append(input, 0, prevat); } for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return(StringBuilderCache.GetStringAndRelease(sb)); } }
/// <summary> /// 设置属性值 /// </summary> /// <param name="elements">要设置属性的元素</param> /// <param name="attributeName">属性名</param> /// <param name="pattern">用于在属性值中查找匹配字符串的正则表达式对象</param> /// <param name="evaluator">替换字符串</param> /// <returns></returns> public static IEnumerable <IHtmlElement> SetAttribute(this IEnumerable <IHtmlElement> elements, string attributeName, Regex pattern, MatchEvaluator evaluator) { if (elements == null) { throw new ArgumentNullException("elements"); } if (attributeName == null) { throw new ArgumentNullException("attributeName"); } if (pattern == null) { throw new ArgumentNullException("pattern"); } elements.NotNull().ForAll(e => e.SetAttribute(attributeName, value => pattern.Replace(value, evaluator))); return(elements); }
public string CreateAndLoadClass() { serial++; string filename = String.Format("{0}match{1}.cs", Path.GetTempPath(), serial); StreamWriter writer = File.CreateText(filename); string className = String.Format("MatchEvaluator{0}", serial); writer.WriteLine("using System;"); writer.WriteLine("using System.Text.RegularExpressions;"); writer.WriteLine("class {0} {{", className); writer.WriteLine(matchEvaluatorString); writer.WriteLine("}"); writer.Close(); Version version = Environment.Version; string runtimePath = String.Format(@"c:\windows\microsoft.net\framework\v{0}.{1}.{2}", version.Major, version.Minor, version.Build); string batchFilename = Path.GetTempPath() + "BuildMatch.bat"; writer = File.CreateText(batchFilename); writer.WriteLine("set path=%path%;{0}", runtimePath); writer.WriteLine("csc /nologo /t:library {0}", filename); writer.Close(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = batchFilename; startInfo.WorkingDirectory = Path.GetTempPath(); startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; Process process = new Process(); process.StartInfo = startInfo; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { string output = process.StandardOutput.ReadToEnd(); string[] lines = output.Split('\n'); output = ""; for (int j = 4; j < lines.Length; j++) { output += lines[j]; } return(output); } try { Assembly assembly = Assembly.LoadFrom(filename.Replace(".cs", ".dll")); Type type = assembly.GetType(className); MethodInfo methodInfo = type.GetMethod("Evaluator"); matchEvaluator = (MatchEvaluator)Delegate.CreateDelegate(typeof(MatchEvaluator), methodInfo); } catch (Exception e) { return(e.ToString()); } return(null); }
/// <summary> /// Replaces all occurrences of the <paramref name="pattern"/> with the recent /// replacement pattern. /// </summary> public static String Replace(String input, String pattern, MatchEvaluator evaluator) { return(Replace(input, pattern, evaluator, RegexOptions.None, DefaultMatchTimeout)); }
public static string Replace(string str, string pattern, MatchEvaluator evaluator) { return(Regex(pattern).Replace(str, evaluator)); }
public string Replace(string input, MatchEvaluator evaluator, RegexOptions options) => Regex.Replace(input, this.Expression, evaluator, options);