本文整理匯總了C#中System.Text.RegularExpressions.Regex.Substring方法的典型用法代碼示例。如果您正苦於以下問題:C# Regex.Substring方法的具體用法?C# Regex.Substring怎麽用?C# Regex.Substring使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Text.RegularExpressions.Regex
的用法示例。
在下文中一共展示了Regex.Substring方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: BeautyMyCode
private string BeautyMyCode(string Source)
{
Source = RemoveStr(Source, new string[] { "\n", "\x09", " " });
Source = new Regex("#include <(.*?)>").Replace(Source, "$0\n");
Source = new Regex(";").Replace(Source, "$0\n");
Source = new Regex("{").Replace(Source, "\n$0\n");
Source = new Regex("}").Replace(Source, "$0\n");
int DeepCount = 0;
for (int i = 0; i < Source.Length; i++)
{
if (Source[i] == '}') DeepCount--;
else if (Source[i] == '{') DeepCount++;
else if (Source[i] == '\n')
{
int NextNewLinePos = Source.IndexOf("\n", i + 1);
if (NextNewLinePos != -1)
{
Console.WriteLine(Source.Substring(i, NextNewLinePos - i));
if (Source.Substring(i, NextNewLinePos - i).Contains("}"))
{
Source = Source.Insert(i + 1, GetManyBlankStr(DeepCount -1));
}
else
{
Source = Source.Insert(i + 1, GetManyBlankStr(DeepCount));
}
}
}
}
return (Source);
}
示例2: ParseAdditionalInformation
protected override void ParseAdditionalInformation()
{
string bankName = new Regex(@"/BBK/.*\|?").Match(statementLine).Value;
if (!string.IsNullOrEmpty(bankName))
{
bankName = bankName.Substring(5);
if (bankName.EndsWith("|"))
{
bankName = bankName.Substring(0, bankName.Length - 1);
}
int vertical = bankName.IndexOf("|");
if (-1 < vertical)
{
bankName = bankName.Substring(0, vertical);
}
bankStatement.CptyBankName = bankName.Trim();
}
AddInformation();
//put tag 86 information to remark
string[] remarks = statementLine.Split(new string[] { TAG_ADDITIONAL_INFO }, StringSplitOptions.None);
if (remarks.Length > 1)
{
bankStatement.Remark = remarks[1];
}
}
示例3: Convert
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var e = value as Event;
if (e != null)
{
if ((String)parameter == "title")
{
return new EventManager().GetTitle(e);
}
if ((String)parameter == "description")
{
var description = new EventManager().GetDescription(e);
if (description != null) {
description = new Regex("\\s+").Replace(description, " ");
if (description.Length > 128) {
description = description.Substring(0, 128).Trim() + "...";
}
}
return description;
}
else if ((String)parameter == "image")
{
return new EventManager().GetImage(e);
}
}
return null;
}
示例4: GetName
private string GetName()
{
string name = new Regex("[^A-Za-z0-9]").Replace(indicatorName,"");
if (name.Length > CharacterLimit)
{
name = name.Substring(0, CharacterLimit);
}
return name;
}
示例5: BitPay
private Dictionary<string, string> _tokenCache; // {facade, token}
/// <summary>
/// Constructor for use if the keys and SIN are managed by this library.
/// </summary>
/// <param name="clientName">The label for this client.</param>
/// <param name="envUrl">The target server URL.</param>
public BitPay(String clientName = BITPAY_PLUGIN_INFO, String envUrl = BITPAY_URL)
{
// IgnoreBadCertificates();
if (clientName.Equals(BITPAY_PLUGIN_INFO))
{
clientName += " on " + System.Environment.MachineName;
}
// Eliminate special characters from the client name (used as a token label). Trim to 60 chars.
string _clientName = new Regex("[^a-zA-Z0-9_ ]").Replace(clientName, "_");
if (_clientName.Length > 60)
{
_clientName = _clientName.Substring(0, 60);
}
_baseUrl = envUrl;
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri(_baseUrl);
this.initKeys();
this.deriveIdentity();
this.tryGetAccessTokens();
}
示例6: SaveParameters
private bool SaveParameters(ListView parameterListView, IDictionary<string, string> parameterList)
{
parameterList.Clear();
List<string> names = new List<string>();
foreach (ListViewItem lvi in parameterListView.Items)
{
// some sanity checking on the parameter names
string param = lvi.SubItems[0].Text;
string name = new Regex("[^a-z0-9_]").Replace(param, "");
if (name == "" || new Regex("[0-9]").IsMatch(name.Substring(0, 1)))
{
MessageBox.Show(string.Format("{0} is not a valid parameter name", param), TemplateName);
parameterListView.Focus();
parameterListView.SelectedItems.Clear();
lvi.Selected = true;
DialogResult = DialogResult.None;
return false;
}
if (names.Contains(name))
{
MessageBox.Show(string.Format("{0}: duplicated parameter", name), TemplateName);
parameterListView.Focus();
parameterListView.SelectedItems.Clear();
lvi.Selected = true;
DialogResult = DialogResult.None;
return false;
}
names.Add(name);
parameterList.Add(lvi.SubItems[0].Text, lvi.SubItems[1].Text);
}
return true;
}
示例7: Render
//.........這裏部分代碼省略.........
//TODO: get alignment data
}else if (tt != null){
throw new Exception("Old style tySh font syntax not implemented, found on layer " + l.Name + ". Use a newer version of Photoshop");
}else if (foundTxt2){
throw new Exception("Txt2 text layer info not supported, found on layer " + l.Name + ". Where did you find this file? What version of photoshop?");
}else{
throw new Exception("No text layer information found on " + l.Name + "!");
}
if (outerGlow != null){
glowColor = outerGlow.Color;
glowFlag = outerGlow.Enabled;
glowWidth = (int)outerGlow.Blur;
glowOpacity = (double)outerGlow.Opacity / 255.0;
}
//Replace text if requested.
if (replacementText != null) text = replacementText;
//Fix newlines
text = text.Replace("\r\n", "\n").Replace("\r", "\n");
//Do graphics stuff
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
using(GraphicsPath path = new GraphicsPath()){
FontFamily fontFamily = null;
StringFormat strformat = null;
try{
FontStyle style = FontStyle.Regular;
//Remove MT
if (fontName.EndsWith("MT")) fontName = fontName.Substring(0, fontName.Length - 2);
//Remove -Bold, -Italic, -BoldItalic
if (fontName.EndsWith("-Bold", StringComparison.OrdinalIgnoreCase)) style |= FontStyle.Bold;
if (fontName.EndsWith("-Italic", StringComparison.OrdinalIgnoreCase)) style |= FontStyle.Italic;
if (fontName.EndsWith("-BoldItalic", StringComparison.OrdinalIgnoreCase)) style |= FontStyle.Bold | FontStyle.Italic;
//Remove from fontName
fontName = new Regex("\\-(Bold|Italic|BoldItalic)$", RegexOptions.IgnoreCase | RegexOptions.IgnoreCase).Replace(fontName, "");
//Remove PS
if (fontName.EndsWith("PS")) fontName = fontName.Substring(0, fontName.Length - 2);
//Find font family
try {
fontFamily = new FontFamily(fontName);
} catch (ArgumentException ae) {
if (IgnoreMissingFonts) {
fontFamily = FontFamily.GenericSansSerif;
} else throw ae;
}
if (fauxBold) style |= FontStyle.Bold;
if (fauxItalic) style |= FontStyle.Italic;
if (underline) style |= FontStyle.Underline;
if (strikethrough) style |= FontStyle.Strikeout;
strformat = new StringFormat();
strformat.LineAlignment = hAlign;
strformat.Alignment = vAlign;
strformat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
if (!horizontal) strformat.FormatFlags |= StringFormatFlags.DirectionVertical;
strformat.Trimming = StringTrimming.None;
path.AddString(text, fontFamily,
(int)style, (float)(fontSize),rect, strformat);
}finally{
示例8: WeatherYandexRu
private void WeatherYandexRu()
{
try
{
var city = string.Empty;
var sr = new StreamReader(LoadSetting);
Line = sr.ReadLine();
sr.Close();
var users = new Users();
var list = users.Read(UsersPath);
if (Line != "Гостем")
{
foreach (var t in list.Where(t => t.Login == Line))
{
textBoxInput.Text = @"Вы зашли под," + t.Login;
city = t.City;
User = t.Login;
break;
}
}
else
{
textBoxInput.Text = @"Вы зашли под," + Line;
User = Line;
ExitFromAccount.Visible = false;
textBoxCityVariable.Text = @"Grodno";
}
var request = WebRequest.Create(@"https://pogoda.yandex.ru/" + city);
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
if (stream != null)
using (var reader = new StreamReader(stream))
{
var data = reader.ReadToEnd();
var temp =
new Regex(
@"<div class=""current-weather__thermometer current-weather__thermometer_type_now"">(?<temp>([+][0-9]{1,2})|(-[0-9]{1,2})|[0]+)")
.Match(data).Groups["temp"].Value;
textBoxWeather.Text = temp + @" °C";
var temp1 =
new Regex(
@"<span class=""current-weather__comment"">(?<temp1>([а-я]+\s[а-я]+)|([а-я]+,\s[а-я]+)|([а-я]+))")
.Match(data).Groups["temp1"].Value;
textBoxWeaher1.Text = temp1.Substring(0, 1).ToUpper() + temp1.Remove(0, 1);
if (city != string.Empty)
{
textBoxCityVariable.Text = city.Substring(0, 1).ToUpper() + city.Remove(0, 1);
}
else
{
city = @"Grodno";
textBoxCityVariable.Text = city.Substring(0, 1).ToUpper() + city.Remove(0, 1);
}
}
}
Log.Info("WeatherConnect");
}
catch (Exception exception)
{
Log.Fatal(exception.Message);
MessageBox.Show(exception.Message);
}
}
示例9: CollapseRegionEvaluator2
private string CollapseRegionEvaluator2(Match m)
{
string retCode = m.Value;
//add rectangle
retCode = retCode.Replace("style='width: 9px; height: 9px'", "style='position: relative; left: -6px; top: 0px; border-color: #808080; border-style: solid; border-width: 1px; background: white; width: 9px; height: 9px'");
string spaces = new Regex("( )+").Match(m.Value).Value;
string regionDescWidthTag = new Regex("#region</span> ([^<]*)</code>").Match(m.Value).Value;
string regionDesc = regionDescWidthTag.Substring(15, regionDescWidthTag.Length - ("#region</span> ").Length - ("</code>").Length);
//add "+" tag
retCode = retCode.Replace("<td style='width: 0px'></td>", "<td style='width: 0px'><span style='position: relative; left: -16px; top: -1px; font: 12px; cursor: hand' onclick='if (this.childNodes[0].innerHTML == \"_\") { this.childNodes[0].innerHTML = \"+\"; this.style.top = \"-1px\"; this.parentNode.nextSibling.childNodes[0].innerHTML = \"<span>" + spaces + "</span><span><font color=gray>" + regionDesc + "</font></span>\"; this.parentNode.nextSibling.childNodes[0].childNodes[1].style.border = \"1px solid gray\"; for (var i = 1 + this.parentNode.parentNode.rowIndex; i < this.parentNode.parentNode.parentNode.childNodes.length; i++) { this.parentNode.parentNode.parentNode.childNodes[i].style.display=\"none\"; if ( this.parentNode.parentNode.parentNode.childNodes[i].childNodes[1].innerText.length > 0 ) { break; } } } else { this.childNodes[0].innerHTML = \"_\"; this.style.top = \"-6px\"; var oldDesc = this.parentNode.nextSibling.childNodes[0].childNodes[1].childNodes[0].innerHTML; this.parentNode.nextSibling.childNodes[0].innerHTML = \"<span>" + spaces + "</span><span><font color=blue>#region </font></span><span></span>\"; this.parentNode.nextSibling.childNodes[0].childNodes[2].innerHTML = oldDesc; for (var i = 1 + this.parentNode.parentNode.rowIndex; i < this.parentNode.parentNode.parentNode.childNodes.length; i++) { this.parentNode.parentNode.parentNode.childNodes[i].style.display=\"block\"; if ( this.parentNode.parentNode.parentNode.childNodes[i].childNodes[1].innerText.length > 0 ) { break; } } }'><font color=#808080 face='Tahoma'>+</font></span></td>");
return retCode;
}
示例10: CollapseRegionEvaluator
private string CollapseRegionEvaluator(Match m)
{
//get region code block
string retCode = m.Value;
string lineHeader = "<tr><td style='width: 0px'><table style='width: 9px; height: 9px'><tr><td></td></tr></table></td><td style='width: 0px'></td><td style='width: 100%'><code style='font: 9pt Tahoma'>";
string lineTailer = "</code></td></tr>";
Regex r = new Regex("^" + lineHeader + @"( )*<span style=\""color: blue\"">#region</span>[^<]*" + lineTailer, RegexOptions.Multiline);
retCode = r.Replace(retCode, new MatchEvaluator(this.CollapseRegionEvaluator2));
//find out #region - #endregion block & add collapse code
string endRegionLinePattern = "<tr><td style='width: 0px'><table style='width: 9px; height: 9px'><tr><td></td></tr></table></td><td style='width: 0px'></td><td style='width: 100%'><code style='font: 9pt Tahoma'>( )*<span style=\"color: blue\">#endregion</span></code></td></tr>";
Regex r2 = new Regex(endRegionLinePattern);
string endRegionLine = r2.Match(retCode).Value;
string formatedEndRegionLine = endRegionLine.Replace("<td style='width: 0px'></td><td style='width: 100%'>", "<td style='width: 0px'><span style='position: relative; left: -12px; font: 12px'><font color=#808080 face='Tahoma'>-</font></span></td><td style='width: 100%'>");
string regionBlock = retCode.Substring(0, retCode.IndexOf(endRegionLine)) + formatedEndRegionLine;
string spaces = new Regex("( )+").Match(regionBlock).Value;
string regionDescWidthTag = new Regex("#region</span> ([^<]*)</code>").Match(regionBlock).Value;
string regionDesc = regionDescWidthTag.Substring(15, regionDescWidthTag.Length - ("#region</span> ").Length - ("</code>").Length);
regionBlock = regionBlock.Replace("</tr><tr><td style='width: 0px'>", "</tr><tr style='display: none'><td style='width: 0px'>");
regionBlock = regionBlock.Substring(0, regionBlock.IndexOf("<code style='font: 9pt Tahoma'>") + "<code style='font: 9pt Tahoma'>".Length) +
"<span>" + spaces + "</span>" + "<span style='border: 1px solid gray'><font color=gray>" + regionDesc + "</font></span>" +
regionBlock.Substring(regionBlock.IndexOf("</code>"));
retCode = regionBlock + retCode.Substring(retCode.IndexOf(endRegionLine) + endRegionLine.Length);
return retCode;
}
示例11: executeDownload
//executeDownload(mh.GetCurrentTrack().GetArtistName(), mh.GetCurrentTrack().GetTrackName(), true);
private async Task executeDownload(string artist, string name, bool tellIfAlreadyExists = false)
{
tryNumber = 0;
time = 0;
startdownload:
try
{
if (downloading)
{
addToLog("Already downloading a song, ignoring requested download", logBox);
return;
}
downloading = true;
string term = artist + " - " + name; //Building search term
term = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars())))).Replace(term, ""); //Removing any invalid characters?
if (string.IsNullOrWhiteSpace(artist) || string.IsNullOrWhiteSpace(name) || mh.IsAdRunning()) //If there is no artist or no name or an ad is running return since theres nothing to download
{
downloading = false;
return;
}
if (term.Length > 16)
if (term.Substring(term.Length - 15).ToLower() == " - original mix")
term = term.Substring(0, term.Length - 15); //Remove "Original Mix"
if (term.Contains(" - feat"))
term = term.Split(new string[] { " - feat" }, StringSplitOptions.None)[0]; //Remove feat
lastDownloaded = term;
if (!File.Exists(browseForFolderBox.Text + lastDownloaded + ".mp3")) //If the song wasent downloaded to the folder already
{
addToLog("Searching MP3Clan for term \"" + term + "\"", logBox);
string pageSource = client.DownloadString(new Uri(string.Format("http://mp3clan.com/mp3_source.php?q={0}", term.Replace(" ", "+")))); //Perform search and get page source
//Perfom a search query in your browser and you can view the source to understand the next line
Match trackId = new Regex("<div class=\"mp3list-table\" id=\"(.+?)\">").Match(pageSource); //Checks if div exists in the page source //What is (.+?)
if (!trackId.Success || string.IsNullOrWhiteSpace(trackId.Groups[1].Value)) //If there was no match or ...I don't know what is trackId.Groups[1].Value? Is it the ID of the div?
{
if (tryNumber < 3) //If try number is less than 3, retry download
{
downloading = false;
tryNumber++;
addToLog("Could not find TrackID, retrying " + tryNumber + "/3", logBox);
goto startdownload;
}
else //If try number is greater than 3, then skip the download/give up
{
addToLog("Could not find TrackID, skipping download", logBox);
downloading = false;
return;
}
}
addToLog("TrackId: " + trackId.Groups[1].Value, logBox);
string dlLink = string.Format("http://mp3clan.com/app/get.php?mp3={0}", trackId.Groups[1].Value);
addToLog("Downloading from link: " + dlLink, logBox);
sw.Start(); //Start the download stopwatch
await Task.WhenAll(downloadFileAsync(dlLink, lastDownloaded)); //Download the track
}
else { if (tellIfAlreadyExists) { addToLog("Song already downloaded", logBox); } downloading = false; } //FIle already downloaded
FileInfo fileInfo = new FileInfo(browseForFolderBox.Text + lastDownloaded + ".mp3");
if (fileInfo.Length < 1000000 && retryIfUnder1Mb.Checked) //If length of file is less than 1mb and retry under 1mb is checked then retry download
{
if (tryNumber < 3)
{
downloading = false;
tryNumber++;
if (File.Exists(browseForFolderBox.Text + lastDownloaded + ".mp3"))
File.Delete(browseForFolderBox.Text + lastDownloaded + ".mp3");
addToLog("File downloaded was under 1MB, redownloading try " + tryNumber + "/3", logBox);
goto startdownload;
}
else
{
downloading = false;
addToLog(term + " failed to download every try, skipping", logBox);
if (Settings.Default.DownloadNotifications)
notifyIcon.ShowBalloonTip(3000, "Download error", "The download for \"" + lastDownloaded + "\" failed to download.", ToolTipIcon.Error);
}
}
downloading = false;
}
catch (Exception e)
{
downloading = false;
tryNumber++;
addToLog("Error downloading file, retrying " + tryNumber + "\n" + e.ToString(), logBox);
goto startdownload;
}
}
示例12: AddInformation
private void AddInformation()
{
string cptyBankName = new Regex(@"/\|?BI/.*?/", RegexOptions.IgnoreCase).Match(statementLine).Value;
if (!string.IsNullOrEmpty(cptyBankName))
{
cptyBankName = cptyBankName.Substring(4);
cptyBankName = cptyBankName.Replace("|", string.Empty).Replace("/", string.Empty).Trim();
bankStatement.CptyBankName = cptyBankName;
}
string cptyAcctNo = new Regex(@"/\|?BA/.*?/", RegexOptions.IgnoreCase).Match(statementLine).Value;
if (!string.IsNullOrEmpty(cptyAcctNo))
{
cptyAcctNo = cptyAcctNo.Substring(4);
cptyAcctNo = cptyAcctNo.Replace("|", string.Empty).Replace("/", string.Empty).Trim();
bankStatement.CptyAcctNo = cptyAcctNo;
}
string cptyAcctName = new Regex(@"/\|?BN/.*?/", RegexOptions.IgnoreCase).Match(statementLine).Value;
if (!string.IsNullOrEmpty(cptyAcctName))
{
cptyAcctName = cptyAcctName.Substring(4);
cptyAcctName = cptyAcctName.Replace("|", string.Empty).Replace("/", string.Empty).Trim();
bankStatement.CptyAcctName = cptyAcctName;
}
}
示例13: EquationsFromParentheses
public static IEnumerable<string> EquationsFromParentheses(string recipe)
{
var equations = new List<string>();
if (string.IsNullOrWhiteSpace(recipe))
{
return equations;
}
recipe = "(" + recipe + ")"; // If this is a duplication of effort, we'll silently ignore it later.
recipe = new Regex(@"\s+").Replace(recipe, string.Empty); // Remove all whitespace.
recipe = LeveledPreparser(recipe);
var multiLetterMatch = invalidLetterFinder.Match(recipe);
if (multiLetterMatch.Success)
{
throw new ArgumentException("The gem \"" + multiLetterMatch.Value + "\" must be a single letter. Gem combinations must be expressed as individual components separated with plus signs and brackets, as needed. For example:\nob → o+b\nob+o → (o+b)+o");
}
var id = 0;
foreach (var c in Gem.GemInitializer)
{
if (recipe.IndexOf(c) > -1)
{
recipe = recipe.Replace(c, id.ToString(CultureInfo.InvariantCulture)[0]);
equations.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", id, c));
id++;
}
}
if (equations.Count == 0)
{
throw new ArgumentException("Recipe did not contain any recognizable gems.");
}
// Scan for plus signs within the formula and add gems together appropriately.
int plus = recipe.IndexOf('+');
string newNum = (id - 1).ToString(CultureInfo.InvariantCulture);
while (plus > -1)
{
string thisCombine;
var close = recipe.IndexOf(')', plus);
if (close >= 0)
{
var open = recipe.LastIndexOf('(', close);
if (open < 0)
{
throw new ArgumentException("Bracket mismatch in formula.");
}
thisCombine = recipe.Substring(open + 1, close - open - 1);
string[] combineGems = thisCombine.Split('+');
if (combineGems.Length != 2)
{
throw new ArgumentException("The formula provided contains more than a single plus sign within a pair of brackets or a term that is over-bracketed (e.g., \"((o+o))\"). These are not currently supported.");
}
if (combineGems[0].Length == 0 || combineGems[1].Length == 0)
{
throw new ArgumentException("Invalid formula part: (" + thisCombine + ")");
}
newNum = id.ToString(CultureInfo.InvariantCulture);
recipe = recipe.Replace("(" + thisCombine + ")", newNum);
equations.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}+{2}", id, combineGems[0], combineGems[1]));
}
else
{
throw new ArgumentException("Bracket mismatch in formula.");
}
plus = recipe.IndexOf('+');
id++;
}
while (recipe.StartsWith("(", StringComparison.Ordinal) && recipe.EndsWith(")", StringComparison.Ordinal))
{
recipe = recipe.Substring(1, recipe.Length - 2);
}
if (recipe != newNum)
{
if (recipe.Contains("("))
{
throw new ArgumentException("Bracket mismatch in formula.");
}
throw new ArgumentException("Invalid recipe.");
}
return equations;
}
示例14: WordWrap
static void WordWrap(string paragraph)
{
paragraph = new Regex(@" {2,}").Replace(paragraph.Trim(), @" ");
var left = Console.CursorLeft;
var top = Console.CursorTop;
var lines = new List<string>();
for (var i = 0; paragraph.Length > 0; i++)
{
lines.Add(paragraph.Substring(0, Math.Min(Console.WindowWidth, paragraph.Length)));
var length = lines[i].LastIndexOf(" ", StringComparison.Ordinal);
if (length > 0)
{
lines[i] = lines[i].Remove(length);
}
paragraph = paragraph.Substring(Math.Min(lines[i].Length + 1, paragraph.Length));
Console.SetCursorPosition(left, top + i);
write(lines[i]);
}
}
示例15: xml_parse
private String xml_parse(String input, String block_name)
{
String temp = new Regex("<" + block_name + ">.*</" + block_name + ">").Match(input).ToString();
return temp.Substring(block_name.Length + 2, temp.Length - 2 * block_name.Length - 5);
}