本文整理汇总了C#中Regex.Replace方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Replace方法的具体用法?C# Regex.Replace怎么用?C# Regex.Replace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Regex
的用法示例。
在下文中一共展示了Regex.Replace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CodeFormat
/// <summary/>
protected CodeFormat()
{
//generate the keyword and preprocessor regexes from the keyword lists
var r = new Regex(@"\w+|-\w+|#\w+|@@\w+|#(?:\\(?:s|w)(?:\*|\+)?\w+)+|@\\w\*+");
string regKeyword = r.Replace(Keywords, @"(?<=^|\W)$0(?=\W)");
string regPreproc = r.Replace(Preprocessors, @"(?<=^|\s)$0(?=\s|$)");
r = new Regex(@" +");
regKeyword = r.Replace(regKeyword, @"|");
regPreproc = r.Replace(regPreproc, @"|");
if (regPreproc.Length == 0)
{
regPreproc = "(?!.*)_{37}(?<!.*)"; //use something quite impossible...
}
//build a master regex with capturing groups
var regAll = new StringBuilder();
regAll.Append("(");
regAll.Append(CommentRegex);
regAll.Append(")|(");
regAll.Append(StringRegex);
if (regPreproc.Length > 0)
{
regAll.Append(")|(");
regAll.Append(regPreproc);
}
regAll.Append(")|(");
regAll.Append(regKeyword);
regAll.Append(")");
RegexOptions caseInsensitive = CaseSensitive ? 0 : RegexOptions.IgnoreCase;
CodeRegex = new Regex(regAll.ToString(), RegexOptions.Singleline | caseInsensitive);
}
示例2: BuildQueryFeaturedItems
protected void BuildQueryFeaturedItems( ref string jsonQuery )
{
string result = @"
,
{
""query"" : {
""range"" : {
""featured_item_start_date"" : {
""lte"" : ""_featured_item_date""
}
}
}
},
{
""query"" : {
""range"" : {
""featured_item_end_date"" : {
""gte"" : ""_featured_item_date""
}
}
}
}
";
Regex re_featured_item = new Regex("_featured_items");
Regex re_featured_item_date = new Regex("_featured_item_date");
if (FeaturedItemDate.Text == "") {
jsonQuery = re_featured_item.Replace(jsonQuery,"");
} else {
result = re_featured_item_date.Replace(result,FeaturedItemDate.Text);
jsonQuery = re_featured_item.Replace(jsonQuery,result);
}
}
示例3: GetHTMLFromURL
protected string GetHTMLFromURL()
{
string HTMLContent = string.Empty;
if (!string.IsNullOrEmpty(_URLToConvert))
{
WebClient webClient = new WebClient();
NameValueCollection queryStringCollection = new NameValueCollection();
queryStringCollection.Add("forPDF", "1");
webClient.QueryString = queryStringCollection;
try
{
HTMLContent = webClient.DownloadString(_URLToConvert);
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
switch (((HttpWebResponse)ex.Response).StatusCode)
{
case HttpStatusCode.NotFound:
litResult.Text = "Web site not found";
break;
default:
litResult.Text = ((HttpWebResponse)ex.Response).StatusDescription;
break;
}
}
}
HTMLContent = HTMLContent.Replace(" media=\"print\"", "");
HTMLContent = HTMLContent.Replace("table.compare td .cell {\r\n padding:8px;\r\n}\r\n", "table.compare td .cell {\r\n padding:0px;\r\n}\r\ntable.compare td.first {font-weight:normal;} table.compare th .cell {color:#000000;height:50px;padding:0;}\r\n");
HTMLContent = HTMLContent.Replace(".single p {\r\n\tpadding:10px 15px;\r\n\tmargin:0;\t\r\n\tfont-size:11px !important;", "h1 {border-bottom-width:0px;padding:3px;margin-bottom:0px;}\r\nh3 {padding:3px;margin:0px;font-size:13px;}\r\n.single p {\r\n\tpadding:2px;\r\n\tmargin:0;\t\r\n\tfont-size:8px !important;");
HTMLContent = HTMLContent.Replace("<table class=\"compare\" id=\"cckfs-table\">", "<table class=\"compare\" id=\"cckfs-table\" style=\"margin-bottom:0px\">");
HTMLContent = HTMLContent.Replace("\r\ntable.compare td, table.compare th {\r\n\tborder:1px solid #ccc;\t\r\n\tfont-size:11px !important;\r\n}", "\r\ntable.compare td, table.compare th {\r\n\tborder:1px solid #ccc;\t\r\n\tfont-size:8px !important;\r\n\tpadding:3px;\r\n}\r\ntable.compare th {\r\n\t\r\n\theight:50px;\r\n}");
HTMLContent = HTMLContent.Replace("<strong>St.George Bank</strong></p>\r\n", "<img width='118' height='35' style='' src='" + HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Images/stgeorgelogo.jpg' /></p>\r\n");
HTMLContent = HTMLContent.Replace("<th>Product name</th>", "<th style=\"width:115px\">Product name</th>");
HTMLContent = HTMLContent.Replace(".container {\r\n\twidth:888px;\r\n\tmargin-top:20px;\t\r\n\tfont-size:11px !important;\r\n}", ".container {\r\n\twidth:888px;\r\n\tmargin-top:0px;\t\r\n\tfont-size:11px !important;\r\n}");
HTMLContent = HTMLContent.Replace("<td align=\"left\"", "<td");
HTMLContent = HTMLContent.Replace("</body>", "<div style=\"font-size:8px;\">©2012 St.George Bank – A Division of Westpac Banking Corporation ABN 33 007 457 141 AFSL and Australian credit licence 233714.</div></body>");
Regex regex = new Regex("<div class=\"single\">");
HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-width:0px\">", 1);
HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-top-width:0px;margin-bottom:5px;\">", 1);
Regex regex2 = new Regex("<p class=\"left\">");
HTMLContent = regex2.Replace(HTMLContent, "<p class=\"left\" style=\"border-right-width:0px;padding:0;\">", 1);
Regex regex3 = new Regex("<p class=\"right\">");
HTMLContent = regex3.Replace(HTMLContent, "<p class=\"right\" style=\"padding:0px;\">", 1);
}
else
{
litResult.Text = "No web site URL";
}
return HTMLContent;
}
示例4: GetHTMLFromURL
protected string GetHTMLFromURL()
{
string HTMLContent = string.Empty;
if (!string.IsNullOrEmpty(_URLToConvert))
{
WebClient webClient = new WebClient();
NameValueCollection queryStringCollection = new NameValueCollection();
queryStringCollection.Add("forPDF", "1");
webClient.QueryString = queryStringCollection;
try
{
HTMLContent = webClient.DownloadString(_URLToConvert);
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
switch (((HttpWebResponse)ex.Response).StatusCode)
{
case HttpStatusCode.NotFound:
litResult.Text = "Web site not found";
break;
default:
litResult.Text = ((HttpWebResponse)ex.Response).StatusDescription;
break;
}
}
}
HTMLContent = HTMLContent.Replace(" media=\"print\"", "");
HTMLContent = HTMLContent.Replace(".single p{padding:15px; margin:0;}", ".single p{padding:5px; margin:0;font-size:8px !important;} table.compare td .cell {padding: 0; } table.compare td.first {font-weight:normal;} table.compare th .cell {color:#000000;} .single p.left {font-size:11px !important;}");
HTMLContent = HTMLContent.Replace("table.compare td,table.compare th{border:1px solid #ccc;}", "table.compare td,table.compare th{border:1px solid #ccc;font-size:8px;padding:3px;height:0;}");
HTMLContent = HTMLContent.Replace("<strong>Bank of Melbourne</strong>", "<img style='margin-left:5px' width='31' height='45' src='" + HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/Images/bankofmelblogo.jpg' /><br/><strong>Bank of Melbourne</strong>");
HTMLContent = HTMLContent.Replace("<th>Product name</th>", "<th style=\"width:115px\">Product name</th>");
HTMLContent = HTMLContent.Replace("<table class=\"compare\">", "<table class=\"compare\" style=\"margin-bottom:0px\">");
HTMLContent = HTMLContent.Replace(".clear{clear:both}", ".clear{clear:both}\r\ntable.compare th .cell { padding:2px;height:25px; } h2, h3 { font-size: 10px; }\r\nh1{margin-bottom:5px !important;padding-bottom:0px !important;;border-bottom-width:0;}\r\nh2{font-size:12px;margin:3px 0;padding:0 !important;}\r\nh3{font-size:14px;margin:0 !important;}");
HTMLContent = HTMLContent.Replace(".container{width:888px;margin-top:20px;}", ".container{width:888px;margin-top:0px;}");
HTMLContent = HTMLContent.Replace("<td align=\"left\"", "<td");
HTMLContent = HTMLContent.Replace("</body>", "<div style=\"font-size:8px;\">©2012 Bank of Melbourne – A Division of Westpac Banking Corporation ABN 33 007 457 141 AFSL and Australian credit licence 233714.</div></body>");
Regex regex = new Regex("<div class=\"single\">");
HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-width:0px;margin-bottom:5px;\">", 1);
HTMLContent = regex.Replace(HTMLContent, "<div class=\"single\" style=\"border-top-width:0px;margin-bottom:5px;\">", 1);
Regex regex2 = new Regex("<p class=\"left\">");
HTMLContent = regex2.Replace(HTMLContent, "<p class=\"left\" style=\"border-right-width:0px;padding:0px;\">", 1);
Regex regex3 = new Regex("<p class=\"right\">");
HTMLContent = regex3.Replace(HTMLContent, "<p class=\"right\" style=\"border-right-width:0px;padding:0px;float:right;text-align:center;\">", 1);
}
else
{
litResult.Text = "No web site URL";
}
return HTMLContent;
}
示例5: Main
static void Main()
{
string input = "<ul><li><a href=\"http://softuni.bg\">SoftUni</a></li></ul>";
string pattern = @"<a(.*href=(.|\n)*?(?=>))>((.|\n)*?(?=<))<\/a>";
Regex regex = new Regex(pattern);
string newPattern = @"[URL$1]$3[/URL]";
regex.Replace(input, newPattern);
if (regex.IsMatch(input) == true)
{
Console.WriteLine(regex.Replace(input,newPattern));
}
}
示例6: Main
static void Main()
{
string givenText = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
Regex regEx = new Regex("<upcase>(.*?)</upcase>");
Console.WriteLine(regEx.Replace(givenText, new MatchEvaluator(UpText)));
// Second Method with Lambda:
Console.WriteLine(regEx.Replace(givenText, matches => matches.Groups[1].Value.ToUpper()));
// 3 Method
Console.WriteLine(regEx.Replace(givenText, delegate(Match matches) { return matches.Groups[1].Value.ToUpper(); }));
}
示例7: Format
public static string Format(string format, string filename)
{
if (String.IsNullOrWhiteSpace(format))
{
format = "{filename}{rand:6}";
}
string ext = Path.GetExtension(filename);
filename = Path.GetFileNameWithoutExtension(filename);
format = format.Replace("{filename}", filename);
format = new Regex(@"\{rand(\:?)(\d+)\}", RegexOptions.Compiled).Replace(format, new MatchEvaluator(delegate(Match match)
{
var digit = 6;
if (match.Groups.Count > 2)
{
digit = Convert.ToInt32(match.Groups[2].Value);
}
var rand = new Random();
return rand.Next((int)Math.Pow(10, digit), (int)Math.Pow(10, digit + 1)).ToString();
}));
format = format.Replace("{time}", DateTime.Now.Ticks.ToString());
format = format.Replace("{yyyy}", DateTime.Now.Year.ToString());
format = format.Replace("{yy}", (DateTime.Now.Year % 100).ToString("D2"));
format = format.Replace("{mm}", DateTime.Now.Month.ToString("D2"));
format = format.Replace("{dd}", DateTime.Now.Day.ToString("D2"));
format = format.Replace("{hh}", DateTime.Now.Hour.ToString("D2"));
format = format.Replace("{ii}", DateTime.Now.Minute.ToString("D2"));
format = format.Replace("{ss}", DateTime.Now.Second.ToString("D2"));
var invalidPattern = new Regex(@"[\\\/\:\*\?\042\<\>\|]");
format = invalidPattern.Replace(format, "");
return format + ext;
}
示例8: Main
static void Main()
{
string currentLine = Console.ReadLine();
List<string> output = new List<string>();
while (currentLine != "END")
{
string pattern = @"\<(div).+(\s*(id|class)\s*=\s*""(.+?)"")";
Regex divAndIdPattern = new Regex(pattern);
Match match = divAndIdPattern.Match(currentLine);
Regex whiteSpaces = new Regex(@"(?<=.)\s+(?=.)");
if (match.Groups.Count == 5)
{
string group1 = match.Groups[1].ToString();
string group2 = match.Groups[2].ToString();
string group4 = match.Groups[4].ToString();
string currentOutput = currentLine.Replace(group1, group4).Replace(group2, "");
output.Add(whiteSpaces.Replace(currentOutput, " "));
}
else
{
string secondPattern = @"<\/(div)>(\s*<!--\s*(.+?)\s*-->)";
Regex secondRegex = new Regex(secondPattern);
Match secondMatch = secondRegex.Match(currentLine);
if (secondMatch.Groups.Count == 4)
{
string group1 = secondMatch.Groups[1].ToString();
string group2 = secondMatch.Groups[2].ToString();
string group3 = secondMatch.Groups[3].ToString();
string currentOutput = currentLine.Replace(group1, group3).Replace(group2, "");
output.Add(currentOutput = whiteSpaces.Replace(currentOutput, " "));
}
else
{
output.Add(currentLine);
}
}
currentLine = Console.ReadLine();
}
foreach (var line in output)
{
Console.WriteLine(line);
}
}
示例9: Decompile
public static string Decompile(string assemblyPath, string identifier = "")
{
var exePath = GetPathToILDasm();
if (!string.IsNullOrEmpty(identifier))
identifier = "/item:" + identifier;
using (var process = Process.Start(new ProcessStartInfo(exePath, String.Format("\"{0}\" /text /linenum {1}", assemblyPath, identifier))
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}))
{
var projectFolder = Path.GetFullPath(Path.GetDirectoryName(assemblyPath) + "\\..\\..\\..").Replace("\\", "\\\\");
projectFolder = String.Format("{0}{1}\\\\", Char.ToUpper(projectFolder[0]), projectFolder.Substring(1));
process.WaitForExit(10000);
var checksumPattern = new Regex(@"^(\s*IL_[0123456789abcdef]{4}: ldstr\s*"")[0123456789ABCDEF]{32,40}""", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
return string.Join(Environment.NewLine, Regex.Split(process.StandardOutput.ReadToEnd(), Environment.NewLine)
.Where(l => !l.StartsWith("// ") && !string.IsNullOrEmpty(l))
.Select(l => l.Replace(projectFolder, ""))
.Select(l => checksumPattern.Replace(l, e => e.Groups[1].Value + "[CHECKSUM]\""))
.ToList());
}
}
示例10: Main
static void Main()
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
string html = Console.ReadLine();
StringBuilder text = new StringBuilder();
//extract p tag content:
string pTagContents = @"<\s*p\s*>([^<]+?)<\s*\/p\s*>";
Regex regexPCont = new Regex(pTagContents, RegexOptions.IgnoreCase);
Regex regexNotSmallLetter = new Regex(@"[^a-z0-9]");
foreach (Match match in regexPCont.Matches(html))
{
String pContent = match.Groups[1].Value;
pContent = regexNotSmallLetter.Replace(pContent, " ");
pContent = Regex.Replace(pContent, @"\s+", " ");
text.Append(pContent);
}
//decrypt text:
for (int i = 0; i < text.Length; i++)
{
char ch = text[i];
if (Char.IsLower(ch))
{
if (ch >= 'a' && ch < 'n')
ch = (char)(ch + 13);
else
ch = (char)(ch - 13);
text[i] = ch;
}
}
Console.WriteLine(text);
}
示例11: Main
static void Main(string[] args)
{
string text;
string patternRepl = @"\s{2,}";
Regex regexRepl = new Regex(patternRepl);
string pattern = @"([^=&]+)=([^&=]+)";
Regex regex = new Regex(pattern);
MatchCollection matches;
var query = new Dictionary<string, List<string>>();
while (!((text = Console.ReadLine()) == "END"))
{
text = text.Replace("%20", " ").Replace("+", " ").Replace("?", "&");
text = regexRepl.Replace(text, " ");
matches = regex.Matches(text);
foreach (Match match in matches)
{
string field = match.Groups[1].ToString().Trim();
string value = match.Groups[2].ToString().Trim();
if (!query.ContainsKey(field))
{
query.Add(field, new List<string>());
}
query[field].Add(value);
}
foreach (string field in query.Keys)
{
Console.Write("{0}=[{1}]", field, string.Join(", ", query[field]));
}
Console.WriteLine();
query.Clear();
}
}
示例12: DeletesText
private static void DeletesText(string firstFileName)
{
//deleting text using regular expresions
//first we read and save the word into List
List<string> nonDeleteText = new List<string>();
StreamReader reader = new StreamReader(firstFileName);
using (reader)
{
string line = reader.ReadLine();
string pattern = "\\btest\\w*";
while (line != null)
{
Regex rgx = new Regex(pattern);
line = rgx.Replace(line, "");
nonDeleteText.Add(line);
line = reader.ReadLine();
}
}
//secondly we are writting the saved List back to the file
StreamWriter writer = new StreamWriter(firstFileName);
using (writer)
{
for (int i = 0; i < nonDeleteText.Count; i++)
{
writer.WriteLine(nonDeleteText[i]);
}
}
}
示例13: Main
static void Main()
{
string input = Console.ReadLine();
Regex regex = new Regex(@"(.)\1+");
Console.WriteLine(regex.Replace(input, "$1"));
}
示例14: Update
public static void Update()
{
if (GameVersion.Version != PlayerSettings.bundleVersion)
{
Debug.Log("Updating GameVersion.cs");
if (!File.Exists(GameVersionPath))
{
Debug.LogError("Could not locate GameVersion.cs!");
return;
}
//Inception!
var regex = new Regex(@"public const string Version = ""(\d+(?:\.\d+)+)""");
string existingCode = File.ReadAllText(GameVersionPath);
var match = regex.Match(existingCode);
if (match.Success)
{
string replacement = match.Value.Replace(match.Groups[1].Value, PlayerSettings.bundleVersion);
existingCode = regex.Replace(existingCode, replacement);
File.WriteAllText(GameVersionPath, existingCode);
}
else
{
Debug.LogError("No Regex match for GameVersion.cs!");
}
}
}
示例15: Main
static void Main()
{
// The regex will match any character (.) and \\1+ will match whatever was captured in the first group.
var text = Console.ReadLine();
var regex = new Regex(@"(.)\1+");
Console.WriteLine(regex.Replace(text, "$1"));
}