本文整理汇总了C#中System.Text.RegularExpressions.Regex.Replace方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Replace方法的具体用法?C# Regex.Replace怎么用?C# Regex.Replace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Text.RegularExpressions.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: Add_log_button_Click
//+ボタンが押されたときに追加
private void Add_log_button_Click(object sender,EventArgs e)
{
if(Browser.Url != null) {
string url = Browser.Url.ToString();
string name = Browser.DocumentTitle;
Regex remove_protocol_name = new Regex("^https?://");
Regex remove_wiki_link = new Regex("#.+$");
Regex remove_kotobank_id = new Regex(@"-\d+?$");
for(int i = 0;i < slist.Rows.Count;i++) {
DataRow site = slist.Rows[i];
string match_chk_str = site["match_str"].ToString();
if(match_chk_str != "") {
if(url.Contains(match_chk_str)) {
string s_str = url;
s_str = remove_protocol_name.Replace(s_str,"");
s_str = s_str.Replace(match_chk_str,"");
if(site["site_name"].ToString() == "Wikipedia" || site["site_name"].ToString() == "Uncyclopedia") {
s_str = remove_wiki_link.Replace(s_str,"");
url = remove_wiki_link.Replace(url,"");
}else if(site["site_name"].ToString() == "コトバンク") {
s_str = remove_wiki_link.Replace(s_str,"");
s_str = remove_kotobank_id.Replace(s_str,"");
url = remove_wiki_link.Replace(url,"");
}
name = site["site_sname"] + " " + s_str;
}
}
}
add_log(url,name);
}
}
示例3: FormatException
/// <summary>
/// INTERNAL
/// </summary>
/// <param name="error">The exception to format.</param>
public static string FormatException(Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
//?? _090901_055134 Regex is used to fix bad PS V1 strings; check V2
Regex re = new Regex("[\r\n]+");
string info =
error.GetType().Name + ":" + Environment.NewLine +
re.Replace(error.Message, Environment.NewLine) + Environment.NewLine;
// get an error record
if (error.GetType().FullName.StartsWith("System.Management.Automation.", StringComparison.Ordinal))
{
object errorRecord = GetPropertyValue(error, "ErrorRecord");
if (errorRecord != null)
{
// process the error record
object ii = GetPropertyValue(errorRecord, "InvocationInfo");
if (ii != null)
{
object pm = GetPropertyValue(ii, "PositionMessage");
if (pm != null)
//?? 090517 Added Trim(), because a position message starts with an empty line
info += re.Replace(pm.ToString().Trim(), Environment.NewLine) + Environment.NewLine;
}
}
}
if (error.InnerException != null)
info += Environment.NewLine + FormatException(error.InnerException);
return info;
}
示例4: ExpressionCleanerAndInputMapBuilder
/// <summary>
/// This method parses a friendly Derived Columns expression entered by the user into a Lineage-ID based
/// expression which is required by SSIS, using a regular-expression based parser.
/// Additionally, it will set the Input Column Usage for any columns found in the expression.
/// </summary>
/// <param name="expression">Expression to be parsed.</param>
/// <param name="transformation">Transformation to use for evaluating the lineage IDs</param>
/// <param name="vi">Transformation Virtual Input used to search for input columns.</param>
/// <param name="inputColumnUsageType">DTSUsageType for columns mapped in this expression.</param>
/// <returns>Expression struct with the pre-processed and post-processed expression.</returns>
public static Expression ExpressionCleanerAndInputMapBuilder(string expression, Transformation transformation, IDTSVirtualInput100 vi, DTSUsageType inputColumnUsageType)
{
Expression exp = new Expression();
exp.OriginalExpression = expression;
exp.ProcessedExpression = expression;
exp.FriendlyExpression = expression;
exp.ContainsId = false;
foreach (IDTSVirtualInputColumn100 vcol in vi.VirtualInputColumnCollection)
{
string regexString = String.Format(CultureInfo.CurrentCulture, "(\"(?:[^\"]|(?<=\\\\)\")*\")|(?<vCol>(?<[email protected]\\[?|:)\\[?\\b{0}\\b\\]?)", Regex.Escape(vcol.Name));
var regex = new Regex(regexString, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
int groupNumber = regex.GroupNumberFromName("vCol");
var processedEme = new ExpressionMatchEvaluatorStruct(groupNumber, "#" + vcol.LineageID, transformation, vi, inputColumnUsageType, vcol);
var friendlyEme = new ExpressionMatchEvaluatorStruct(groupNumber, vcol.Name, null, null, DTSUsageType.UT_IGNORED, null);
exp.ProcessedExpression = regex.Replace(exp.ProcessedExpression, new MatchEvaluator(processedEme.EvaluateMatch));
exp.FriendlyExpression = regex.Replace(exp.FriendlyExpression, new MatchEvaluator(friendlyEme.EvaluateMatch));
}
if (exp.ProcessedExpression != exp.OriginalExpression)
{
exp.ContainsId = true;
}
return exp;
}
示例5: DoDeleteWordInBrackets
private void DoDeleteWordInBrackets(Word word)
{
var regex = new Regex(@"\(.*\)");
word.BaseWord = regex.Replace(word.BaseWord, string.Empty);
word.Translation = regex.Replace(word.Translation, string.Empty);
}
示例6: Save
internal bool Save(string name, string output, bool withSample =true)
{
WithSample = withSample;
int index = name.LastIndexOf('\\');
OrgFilename = name.Substring(index + 1, name.LastIndexOf('.') - index - 1);
Dir = output;
OrgDir = name.Substring(0, index + 1); // with \\
Regex reg = new Regex(@"[\\/\:\*\?\<\>\|\\""]");
Artist = reg.Replace(Artist, "");
Title = reg.Replace(Title, "");
Diff = reg.Replace(Diff, "");
Filename = string.Format("{0} - {1} ({2}) [{3}].osu", Artist, Title, "BMXC_V1", Diff);
if(File.Exists(Dir+Filename))
Filename = "("+OrgFilename+")"+Filename;
//no notes in special column, convert to normal map.
if (!Special)
{
Column--;
}
doSort();
calculateTime();
if(withSample)
calculateEvent();
calculateNote();
writeToFile();
return true;
}
示例7: ShouldNotRemoveLineBreaksFromSqlQueries
public void ShouldNotRemoveLineBreaksFromSqlQueries()
{
using (var spy = new SqlLogSpy())
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
const string sql = @"
select Id
from Entity
where 1=1";
var query = s.CreateSQLQuery(sql);
Assert.DoesNotThrow(() => query.List());
string renderedSql = spy.Appender.GetEvents()[0].RenderedMessage;
Regex whitespaces = new Regex(@"\s+", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
Assert.AreEqual(
string.Compare(
whitespaces.Replace(sql, " ").Trim(),
whitespaces.Replace(renderedSql, " ").Trim(),
true
),
0
);
}
}
示例8: NewTestRequest_WithUrl_ShouldOutputInCorrectFormat
public void NewTestRequest_WithUrl_ShouldOutputInCorrectFormat()
{
const string xml = @"<test_set>
<applications type=""array"">
<application>
<code>chrome2</code>
</application>
<application>
<code>ie7</code>
</application>
<application>
<code>ie6</code>
</application>
</applications>
<save_defaults>false</save_defaults>
<use_defaults>false</use_defaults>
<url>http://google.com</url>
</test_set>";
var pageClients = new List<TestingApplication>();
pageClients.Add(new TestingApplication(){ApplicationCode = "chrome2",ResultType = "page"});
pageClients.Add(new TestingApplication() {ApplicationCode = "ie7", ResultType = "page"});
pageClients.Add(new TestingApplication() {ApplicationCode = "ie6", ResultType = "page"});
var request = new CreatePageTestRequest(pageClients, "http://google.com");
var cleanSpacing = new Regex(@"\s+", RegexOptions.None);
var cleanRequest = cleanSpacing.Replace(request.ToString(), "");
var cleanXml = cleanSpacing.Replace(xml, "");
Console.WriteLine(cleanRequest);
Console.WriteLine(cleanXml);
Assert.That(cleanRequest == cleanXml);
}
示例9: SiteList
private List<SiteCoord> SiteList(string searchString)
{
//Return value
List<SiteCoord> results = new List<SiteCoord>();
//Regex for site name
Regex rgx = new Regex("[^a-zA-Z0-9]");
//Read RVSite available
var _sites = sites.GetAll();
//Remove characters from search string
searchString = rgx.Replace(searchString, "").ToUpper();
if (searchString != null)
{
//Filter by RV Site
foreach (var _site in _sites)
{
string rvsiteShort = rgx.Replace(_site.RVSite, "").ToUpper();
if (rvsiteShort.Contains(searchString))
{
results.Add(new SiteCoord(_site.id, _site.RVSite, _site.latitude, _site.longitude));
}
}
}
return results.OrderBy(q => q.Label).ToList();
}
示例10: button1_Click
private void button1_Click(object sender, EventArgs e)
{
//Apply
Regex replacer = new Regex(textBox1.Text);
foreach (var node in nodes)
node.node_name = replacer.Replace(node.node_name, textBox2.Text);
//Update visual list
for (int i = 0; i < list_box.Items.Count; i++)
{
var nd = list_box.Items[i];
list_box.Items.RemoveAt(i);
list_box.Items.Insert(i, nd);
}
//Refactoring names in lists
foreach (node_info node in node_gen.all_nodes)
{
foreach (var subnode in node.subnodes)
{
if (subnode is extended_simple_element)
{
extended_simple_element sn = (subnode as extended_simple_element);
string list_type = sn.list_type;
if (list_type != "")
sn.list_type = replacer.Replace(list_type, textBox2.Text);
}
}
}
}
示例11: GetSpeedByNoise
public List<Tuple<double, double>> GetSpeedByNoise(StreamReader fs)
{
List<string> strs = new List<string>();
Regex dataRegex = new Regex(@"y = \d");
while (!fs.EndOfStream)
{
var str = fs.ReadLine();
if (dataRegex.IsMatch(str))
{
strs.Add(str);
}
}
var velocAndNoise = new List<Tuple<double, double>>(strs.Count);
Regex notNumbers = new Regex(@"[A-Za-z]");
Regex dotRegex = new Regex(@"\.");
for (int i = 0; i < strs.Count; i++)
{
string veloc = dotRegex.Replace(notNumbers.Replace(strs[i].Split('=')[1], ""), ",");
string noise = dotRegex.Replace(notNumbers.Replace(strs[i].Split('=')[2], ""), ",");
velocAndNoise.Add(new Tuple<double, double>(Convert.ToDouble(noise), Convert.ToDouble(veloc)));
}
fs.BaseStream.Seek(0, SeekOrigin.Begin);
return velocAndNoise;
}
示例12: NewTestRequest_WithSubjectAndBody_ShouldOutputInCorrectFormat
public void NewTestRequest_WithSubjectAndBody_ShouldOutputInCorrectFormat()
{
const string xml = @"<test_set>
<applications type=""array"">
<application>
<code>outlookcom</code>
</application>
<application>
<code>gmailnew</code>
</application>
<application>
<code>notes8</code>
</application>
</applications>
<save_defaults>false</save_defaults>
<use_defaults>false</use_defaults>
<email_source>
<body><![CDATA[<html><body><p>Here is an email body!</p></body></html>]]></body>
<subject>My test email to Litmus</subject>
</email_source>
</test_set>";
var emailClients = new List<TestingApplication>();
emailClients.Add(new TestingApplication() { ApplicationCode = "outlookcom", ResultType = "email" });
emailClients.Add(new TestingApplication() { ApplicationCode = "gmailnew", ResultType = "email" });
emailClients.Add(new TestingApplication() { ApplicationCode = "notes8", ResultType = "email" });
var request = new CreateEmailTestRequest(emailClients, "My test email to Litmus", "<html><body><p>Here is an email body!</p></body></html>");
var cleanSpacing = new Regex(@"\s+", RegexOptions.None);
var cleanRequest = cleanSpacing.Replace(request.ToString(), "");
var cleanXml = cleanSpacing.Replace(xml, "");
Console.WriteLine(cleanRequest);
Console.WriteLine(cleanXml);
Assert.That(cleanRequest == cleanXml);
}
示例13: Application_BeginRequest
private void Application_BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
foreach (var rule in GetRuleList())
{
var lookFor = "^" + ResolveUrl(app.Request.ApplicationPath, rule.LookFor) + "$";
var re = new Regex(lookFor, RegexOptions.IgnoreCase);
if (IsHttpUrl(rule.LookFor))
{
if (re.IsMatch(app.Request.Url.AbsoluteUri))
{
var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Url.AbsoluteUri, rule.SendTo));
RewritePath(app.Context, sendTo);
break;
}
}
else
{
if (re.IsMatch(app.Request.Path))
{
var sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Path, rule.SendTo));
RewritePath(app.Context, sendTo);
break;
}
}
}
}
示例14: NewTestRequest_WithOnlyTestingApplications_ShouldOutputInCorrectFormat
public void NewTestRequest_WithOnlyTestingApplications_ShouldOutputInCorrectFormat()
{
const string xml = @"<test_set>
<applications type=""array"">
<application>
<code>outlookcom</code>
</application>
<application>
<code>gmailnew</code>
</application>
<application>
<code>notes8</code>
</application>
</applications>
<save_defaults>false</save_defaults>
<use_defaults>false</use_defaults>
</test_set>";
var emailClients = new List<TestingApplication>();
emailClients.Add(new TestingApplication(){ApplicationCode = "outlookcom",ResultType = "email"});
emailClients.Add(new TestingApplication() {ApplicationCode = "gmailnew", ResultType = "email"});
emailClients.Add(new TestingApplication() {ApplicationCode = "notes8", ResultType = "email"});
var request = new CreateEmailTestRequest(emailClients);
var cleanSpacing = new Regex(@"\s+", RegexOptions.None);
var cleanRequest = cleanSpacing.Replace(request.ToString(), "");
var cleanXml = cleanSpacing.Replace(xml, "");
Assert.That(cleanRequest == cleanXml);
}
示例15: Format
private static string m_StrOperationFormatRegEx = @"(\)\s*[-+/*])\s*(\()";//скобки рядом с арифметической операцией в весовой части
/// <summary>
/// Форматировать.
/// </summary>
/// <param name="strUpdateCmd"></param>
/// <returns></returns>
public static string Format(string strUpdateCmd)
{
//Пока распознает не все возможные варианты текста команды обновления, форматирует не идеально, но приемлемо
//Сделать 1 рег. выражением нет смысла: 1. Выражение будет оч. сложное 2.Будет очень долго работать
//(десятки секунд +, а надо формат-ть практически "на лету" при выводе куда-то )
string strFormmattedCmd = String.Empty;
Regex regEx = new Regex(m_Str1stFormatStepRegEx, RegexOptions.IgnoreCase);
//1 совпадение - вся строка, разбитая на именованые группы, которые представляют собой основные куски запроса
GroupCollection grpCol = regEx.Match(strUpdateCmd).Groups;
//Форматирование координат Tuple СЛЕВА от знака присваивания в SET
regEx = new Regex(m_StrTupleAndValueFormatRegEx, RegexOptions.IgnoreCase);
string strTuple = regEx.Replace(grpCol["TuplePart"].Value, Environment.NewLine + "$1");
//Форматирование координат Tuple СПРАВА от знака присваивания в SET
string strValue = regEx.Replace(grpCol["ValuePart"].Value, "$1" + Environment.NewLine);
string strWeight = String.Empty;
if (grpCol["WeightPart"].Value != null && grpCol["WeightPart"].Value != String.Empty)//Если есть весовая часть
{
//Форматирование веса с учетом того, что могут попадаться вызовы ф-ций
regEx = new Regex(m_StrWeightFormatRegEx, RegexOptions.IgnoreCase);
strWeight = regEx.Replace(grpCol["WeightPart"].Value, "$1" + Environment.NewLine);
//Форматирование арифметич операций в весе, если есть
regEx = new Regex(m_StrOperationFormatRegEx, RegexOptions.IgnoreCase);
strWeight = regEx.Replace(strWeight, String.Format("$1{0}$2{0}", Environment.NewLine));
}
strFormmattedCmd = String.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{7}{0}{8}{0}{9}", Environment.NewLine,
grpCol["UpdatePart"].Value, grpCol["SetPart"].Value, strTuple, grpCol["EqualPart"].Value,
strValue, grpCol["UsePart"].Value, grpCol["ByPart"].Value, strWeight, grpCol["EndParenthesis"].Value);
return strFormmattedCmd;
}
开发者ID:SmallMobile,项目名称:ranet-uilibrary-olap.latest-unstabilized,代码行数:36,代码来源:OlapCmdUpdateStringFormatter.cs