本文整理汇总了C#中System.Text.RegularExpressions.Regex.NextMatch方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.NextMatch方法的具体用法?C# Regex.NextMatch怎么用?C# Regex.NextMatch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Text.RegularExpressions.Regex
的用法示例。
在下文中一共展示了Regex.NextMatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetNumberFromText
public static int GetNumberFromText(this string text)
{
string clearNumberStr = text.GetMatchGroup("(?<key>[一二三四五六七八九十百千万亿兆零壹贰叁肆伍陆柒捌玖0123456789]+)").Groups["key"].Value.IsNull("0");
int result = 0;
Match m = new Regex("[一二三四五六七八九]?十|[一二三四五六七八九]+百|[一二三四五六七八九]+千|[一二三四五六七八九]+万|[一二三四五六七八九]+", RegexOptions.None).Match(clearNumberStr);
while (m.Success)
{
result += m.Groups[0].Value.Replace("一", "1")
.Replace("二", "2")
.Replace("三", "3")
.Replace("四", "4")
.Replace("五", "5")
.Replace("六", "6")
.Replace("七", "7")
.Replace("八", "8")
.Replace("九", "9")
.Replace("十", "0")
.Replace("百", "00")
.Replace("千", "000")
.Replace("万", "0000")
.ToInt32()
;
m = m.NextMatch();
}
return result;
}
示例2: StripHtml
private static string StripHtml(string htmlText)
{
if (string.IsNullOrEmpty(htmlText))
{
return string.Empty;
}
htmlText = htmlText.Replace("<br>", "\n");
htmlText = htmlText.Replace(" ", " ");
var urls = new List<string>();
var match = new Regex(@"href=([""']+)(?<Url>(([^""'])+))").Match(htmlText);
while(match.Success)
{
urls.Add(match.Groups["Url"].Captures[0].Value);
match = match.NextMatch();
}
var urlPlaceholder = "-url-";
htmlText = Regex.Replace(htmlText, @"<a.*?>", urlPlaceholder);
htmlText = Regex.Replace(htmlText, @"<.*?>", string.Empty);
int location = 0;
foreach (var url in urls)
{
location = htmlText.IndexOf(urlPlaceholder, location);
if(location == -1)
{
break;
}
htmlText = htmlText.Remove(location, urlPlaceholder.Length);
htmlText = htmlText.Insert(location, string.Format(" ({0}) ", url));
}
return htmlText;
}
示例3: GetTag
private List<string> GetTag(string s)
{
List<string> tmp = new List<string> { };
Match matc = new Regex(@"#[a-zA-Z0-9_]+").Match(s);
while (matc.Success)
{
tmp.Add(matc.Value);
matc = matc.NextMatch();
}
s = null; matc = null;
return tmp;
}
示例4: AsciiToNative
/// <summary>
/// 识别Js中的Ascii 字符串为中文
/// </summary>
/// <param name="AsciiString"></param>
/// <returns></returns>
public static string AsciiToNative(this string AsciiString)
{
string result = AsciiString;
Match m = new Regex("(\\\\u([\\w]{4}))").Match(AsciiString);
while (m.Success)
{
string v = m.Value;
string word = v.Substring(2);
byte[] codes = new byte[2];
int code = Convert.ToInt32(word.Substring(0, 2), 16);
int code2 = Convert.ToInt32(word.Substring(2), 16);
codes[0] = (byte)code2;
codes[1] = (byte)code;
result = result.Replace(v, Encoding.Unicode.GetString(codes));
m = m.NextMatch();
}
return result;
//MatchCollection mc = Regex.Matches(AsciiString, "(\\\\u([\\w]{4}))");
//if (mc != null && mc.Count > 0)
//{
// StringBuilder sb = new StringBuilder();
// foreach (Match m2 in mc)
// {
// string v = m2.Value;
// string word = v.Substring(2);
// byte[] codes = new byte[2];
// int code = Convert.ToInt32(word.Substring(0, 2), 16);
// int code2 = Convert.ToInt32(word.Substring(2), 16);
// codes[0] = (byte)code2;
// codes[1] = (byte)code;
// sb.Append(Encoding.Unicode.GetString(codes));
// }
// return sb.ToString();
//}
//else
//{
// return AsciiString;
//}
}
示例5: Convert
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string param = (parameter as string), RegexTemplate = @"(\w+)\((\w+,\w+,\w+)\)";
if (Regex.IsMatch(param, RegexTemplate))
{
//Окончание предложения в тексте, value обязательно должен быть числом
double x = GetValueNumber(value);
Match matc = new Regex(RegexTemplate).Match(param);
while (matc.Success)
{
GroupCollection g = new Regex(RegexTemplate).Match(matc.Value).Groups;
string FinText = g[1] + Engine.Class.FinText.get((g[2].Value.Split(',')[0]), (g[2].Value.Split(',')[1]), (g[2].Value.Split(',')[2]), (long)x);
string tmp = Regex.Replace(param, (g[1] + @"\((\w+,\w+,\w+)\)"), FinText);
param = tmp; tmp = null; FinText = null; matc = matc.NextMatch();
}
//Проверка, нужно ли возвращать все данные или вернуть "{0:N0}" для стринг формата
if (Regex.IsMatch(param, "ValueNull"))
{
return Regex.Replace(param, "ValueNull", "{0:N0}");
}
else
{
return Regex.Replace(param, "value", string.Format("{0:N0}", x).Replace(((char)160), ','));
}
}
else
{
//Простая замена строки, value может быть как string так и число, но возвращаеться всегда string
if (Regex.IsMatch(param, "ValueNull"))
{
return Regex.Replace(param, "ValueNull", "{0:N0}");
}
else
{
return "Не реализованно";
}
}
}
示例6: colorAll
public void colorAll()
{
this.running = true;
this.rich.SelectAll();
this.resetFont();
string text = this.rich.Text;
text.ToLower();
this.rich.Visible = false;
int selectionStart = this.rich.SelectionStart;
foreach (Keyword keyword in this.keywords)
{
for (Match match = new Regex(@"\b" + keyword.Value + @"\b").Match(text); match.Success; match = match.NextMatch())
{
this.rich.Select(match.Index, match.Length);
this.rich.SelectionColor = Color.FromName(keyword.Color);
this.rich.ClearUndo();
try
{
FontFamily fontFamily = this.rich.SelectionFont.FontFamily;
float size = this.rich.SelectionFont.Size;
this.rich.SelectionFont = new Font(this.normalFont.FontFamily, this.normalFont.Size, keyword.Bold ? FontStyle.Bold : FontStyle.Regular);
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
}
for (Match match2 = new Regex(@"\-\-[^\n]*(?!=\n)").Match(this.rich.Text); match2.Success; match2 = match2.NextMatch())
{
this.rich.Select(match2.Index, match2.Length);
this.rich.SelectionColor = Color.Green;
}
this.rich.Visible = true;
this.rich.Focus();
this.rich.Select(selectionStart, 0);
this.resetFont();
this.running = false;
}
示例7: Search
public override void Search()
{
string langStr = TextMiningUtils.GetLanguageCode(mLanguage);
mResultSet.Inner.Clear();
if (mCache == null || !mCache.GetFromCache("GoogleDefine", mLanguage, mQuery, mResultSetMaxSz, ref mTotalHits, ref mResultSet))
{
int i = 0;
string defHtml = WebUtils.GetWebPage(string.Format("http://www.google.com/search?defl={0}&q=define%3A{1}", langStr, HttpUtility.UrlEncode(mQuery))); // throws WebException
Match defMatch = new Regex("<li>(?<def>[^<]*)(<br><a href=\"(?<href>[^\"]*))?", RegexOptions.Singleline).Match(defHtml);
while (defMatch.Success)
{
string def = HttpUtility.HtmlDecode(defMatch.Result("${def}").Trim());
string href = defMatch.Result("${href}");
string url = null;
Match matchUrl = new Regex("&q=(?<url>[^&]*)").Match(href);
if (matchUrl.Success) { url = HttpUtility.UrlDecode(matchUrl.Result("${url}")); }
mResultSet.Inner.Add(new SearchEngineResultItem(mQuery, def, url, ++i));
defMatch = defMatch.NextMatch();
}
string lastUrl = null;
for (int j = mResultSet.Count - 1; j >= 0; j--)
{
if (mResultSet[j].Url == null) { mResultSet[j].SetUrl(lastUrl); }
else { lastUrl = mResultSet[j].Url; }
}
mTotalHits = mResultSet.Count;
if (mCache != null)
{
mCache.PutIntoCache("GoogleDefine", mLanguage, mQuery, mTotalHits, mResultSet);
}
if (mResultSetMaxSz < mResultSet.Count)
{
mResultSet.Inner.RemoveRange(mResultSetMaxSz, mResultSet.Count - mResultSetMaxSz);
}
}
}
示例8: AddTag
private void AddTag(Engine.InfoClass.job.hashTag job, string tag)
{
if (tag == null)
return;
List<string> tmp = new List<string> { };
Match matc = new Regex(@"#[\w0-9_]+").Match(tag);
while (matc.Success)
{
//Если тег не дубликат и в нем больше 2х символов
if (matc.Value.Length > 3 && !job.HashTag.Exists(x => x.ToLower().Trim() == matc.Value.ToLower().Trim()))
{
tmp.Add(matc.Value);
}
matc = matc.NextMatch();
}
//Добовляем теги
if (tmp.Count != 0) { job.HashTag.AddRange(tmp); }
//Чистим ресурсы
tag = null; tmp = null; matc = null; job = null;
}
示例9: Work
//.........这里部分代码省略.........
errorCode = WebExceptionStatus.Success;
error = null;
start = DateTime.Now;
ccc.Add(new CommandContainer(request, "Request")); commander.Request = request;
try { scriptBeforeResult = request.ScriptBefore == null ? null : (ccc.ExecuteCommand(request.ScriptBefore) ?? "").ToString(); }
catch (Exception e) { scriptBeforeResult = e.Message; }
IsWaiting = true;
try
{
if (request.PostData == null)
{
webClient.Headers.Remove(HttpRequestHeader.ContentType);
if (commander.Burning)
{
response = null;
error = "Burning";
swHttp.Start();
webClient.DownloadStringAsync(new Uri(request.Url));
webClient.CancelAsync();
}
else
{
swHttp.Start();
response = webClient.DownloadString(request.Url);
}
}
else
{
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
if (commander.Burning)
{
response = null;
error = "Burning";
swHttp.Start();
webClient.UploadStringAsync(new Uri(request.Url), request.PostData);
webClient.CancelAsync();
}
else
{
swHttp.Start();
response = webClient.UploadString(request.Url, request.PostData);
}
}
}
catch (WebException we)
{
response = null;
errorCode = we.Status;
error = we.Message;
}
catch(Exception e)
{
response = null;
errorCode = WebExceptionStatus.UnknownError;
error = e.Message;
}
swHttp.Stop();
IsWaiting = false;
result = new TestRequestResult(request)
{
Duration = swHttp.Elapsed,
Start = start,
WorkerId = Id,
Status = errorCode,
Valid = request.ResultValidation == null || response == null ?
default(Nullable<bool>) : new Regex(request.ResultValidation, RegexOptions.Singleline).Match(response).Success,
Length = response == null ? default(Nullable<int>) : response.Length,
Iteration = Iterations,
ScriptBeforeResult = scriptBeforeResult,
Error = error,
};
if (request.ResultDataExtract != null && response != null)
{
StringBuilder data = new StringBuilder();
Match match = new Regex(request.ResultDataExtract, RegexOptions.Singleline).Match(response);
while (match.Success)
{
data.Append(match.Value);
match = match.NextMatch();
if (match.Success) { data.Append(request.ResultDataSeparator); }
}
result.DataExtracted = data.ToString();
}
ccc.StoredValues["Response"] = response; commander.ResponseString = response;
ccc.Remove("Result"); ccc.Add(new CommandContainer(result, "Result")); commander.Result = result;
try { result.ScriptAfterResult = request.ScriptAfter == null ? null : (ccc.ExecuteCommand(request.ScriptAfter) ?? "").ToString(); }
catch (Exception e) { result.ScriptAfterResult = e.Message; }
ccc.Remove("Request");
swHttp.Reset();
this.testResults.Add(result);
Requests++;
}
}
swIteration.Stop();
LastIterationRunTime = swIteration.Elapsed;
swIteration.Reset();
}
IsRunning = false;
Done = Iterations == MaxIterations;
}
示例10: Preprocess
protected static string Preprocess(string origScript, ISQLDatabase database)
{
// Replace simple types
StringBuilder result = new StringBuilder(origScript);
result = result.Replace("%TIMESTAMP%", GetType(typeof(DateTime), database)).
Replace("%CHAR%", GetType(typeof(Char), database)).
Replace("%BOOLEAN%", GetType(typeof(Boolean), database)).
Replace("%SINGLE%", GetType(typeof(Single), database)).
Replace("%DOUBLE%", GetType(typeof(Double), database)).
Replace("%SMALLINT%", GetType(typeof(Int16), database)).
Replace("%INTEGER%", GetType(typeof(Int32), database)).
Replace("%BIGINT%", GetType(typeof(Int64), database)).
Replace("%GUID%", GetType(typeof(Guid), database)).
Replace("%BINARY%", GetType(typeof(byte[]), database));
// For extended replacements: First collect all patterns to be replaced...
IDictionary<string, string> replacements = new Dictionary<string, string>();
string interimStr = result.ToString();
// %STRING([N])%
Match match = new Regex(@"%STRING\((\d*)\)%").Match(interimStr);
while (match.Success)
{
string pattern = match.Value;
if (!replacements.ContainsKey(pattern))
{
uint length = uint.Parse(match.Groups[1].Value);
replacements.Add(pattern, database.GetSQLVarLengthStringType(length));
}
match = match.NextMatch();
}
// %STRING_FIXED([N])%
match = new Regex(@"%STRING_FIXED\((\d*)\)%").Match(interimStr);
while (match.Success)
{
string pattern = match.Value;
if (!replacements.ContainsKey(pattern))
{
uint length = uint.Parse(match.Groups[1].Value);
replacements.Add(pattern, database.GetSQLFixedLengthStringType(length));
}
match = match.NextMatch();
}
// %CREATE_NEW_GUID% / %GET_LAST_GUID%
string lastGuid = null;
match = new Regex(@"(%CREATE_NEW_GUID%)|(%GET_LAST_GUID%)").Match(interimStr);
while (match.Success)
{
Group g;
if ((g = match.Groups[1]).Success) // %CREATE_NEW_GUID% matched
result.Replace("%CREATE_NEW_GUID%", lastGuid = Guid.NewGuid().ToString("B"), g.Index, g.Length);
else if ((g = match.Groups[2]).Success) // %GET_LAST_GUID% matched
result.Replace("%GET_LAST_GUID%", lastGuid, g.Index, g.Length);
match = match.NextMatch();
}
// ... then do the actual replacements
result = replacements.Aggregate(result, (current, replacement) => current.Replace(replacement.Key, replacement.Value));
return result.ToString();
}
示例11: getBoxName
private void getBoxName(string message)
{
int index = 0;
string str = "";
string pattern = "<td class=\"ManageFoldersFolderNameCol\"><div.*?href=\"(?<BoxUrl>[^\"]+)\".*?>(?<BoxNamme>[^<]+)</a[\\s\\S]+?<\\/td>";
Match match = new Regex(pattern).Match(message);
if (match.Length < 1)
{
base.ShowMessage("取箱子失败!");
}
else
{
int num2 = 0;
while (match.Success)
{
this.boxList[num2].boxname = base.BoxName = match.Groups["BoxNamme"].Value;
this.boxList[num2].boxUrl = str = match.Groups["BoxUrl"].Value;
this.boxList[num2].boxid = base.putstr(str, "FolderID=", "&", 0);
match = match.NextMatch();
num2++;
}
index = 0;
while (index < num2)
{
string url = base.Host + this.boxList[index].boxUrl;
this.cookie = this.cookieTemp;
base.MyStringBuilder.Remove(0, base.MyStringBuilder.Length);
base.streamControl = true;
base.MyStringBuilder = this.Request(url);
this.getPages(base.MyStringBuilder.ToString(), index);
index++;
}
lock (SelMailBoxL)
{
for (index = 0; index < num2; index++)
{
string strSql = string.Concat(new object[] { "select count(*) from MailBoxList where 序号='", base.m_NO, "' and MailBoxName = '", this.boxList[index].boxname, "'" });
if (Convert.ToInt32(GlobalValue.PopMainForm.ExecuteSQL(strSql)) == 0)
{
strSql = string.Concat(new object[] { "insert into MailBoxList (序号,MailBoxName)values('", base.m_NO, "','", this.boxList[index].boxname, "');" });
GlobalValue.PopMainForm.ExecuteSQL(strSql);
}
}
}
}
}
示例12: fetch
public void fetch(string url)
{
Console.WriteLine("{0}, Thread Id= {1}", url, Thread.CurrentThread.ManagedThreadId);
try
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.UserAgent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7";
request.Referer = "http://www.google.com";
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream,Encoding.UTF8);
string responseFromServer = reader.ReadToEnd();
response.Close();
Match proxyMatch = new Regex(@"([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5})", RegexOptions.IgnoreCase).Match(responseFromServer);
while (proxyMatch.Success)
{
Group g = proxyMatch.Groups[0];
Thread.MemoryBarrier();
Ips.Add(g.ToString());
Thread.MemoryBarrier();
proxyMatch = proxyMatch.NextMatch();
}
Match httpMatch = new Regex(@"<(?<Tag_Name>(a))\b[^>]*?\b(?<URL_Type>(?(1)href))\s*=\s*(?:""(?<URL>(?:\\""|[^""])*)""|'(?<URL>(?:\\'|[^'])*)')", RegexOptions.IgnoreCase).Match(responseFromServer);
while (httpMatch.Success)
{
Thread.MemoryBarrier();
glob_visited.Add(httpMatch.Groups[4].ToString());
Thread.MemoryBarrier();
httpMatch = httpMatch.NextMatch();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
示例13: GetNumberFromTitle
public static int GetNumberFromTitle(this string title)
{
Match mc = new Regex("第[一二三四五六七八九〇零十百千万1234567890]+章|引子", RegexOptions.None).Match(title);
if (mc.Success)
{
string str_chineseNumber = mc.Groups[0].Value;
str_chineseNumber = str_chineseNumber.Replace("第", "").Replace("章", "").Replace("引子", "0");
int result = 0;
Match m = new Regex("[一二三四五六七八九]?十|[一二三四五六七八九]+百|[一二三四五六七八九]+千|[一二三四五六七八九]+万|[一二三四五六七八九]+", RegexOptions.None).Match(str_chineseNumber);
while (m.Success)
{
result += m.Groups[0].Value.Replace("一", "1")
.Replace("二", "2")
.Replace("三", "3")
.Replace("四", "4")
.Replace("五", "5")
.Replace("六", "6")
.Replace("七", "7")
.Replace("八", "8")
.Replace("九", "9")
.Replace("十", "0")
.Replace("百", "00")
.Replace("千", "000")
.Replace("万", "0000")
.ToInt32()
;
m = m.NextMatch();
}
return result;
}
else
{
return -1;
}
}
示例14: ReplaceTagContent
/// <summary>
/// 替换标签
/// </summary>
/// <param name="TmpString"></param>
/// <returns></returns>
public string ReplaceTagContent(string TmpString)
{
Match mc = new Regex("\\[(?<key>.*?)\\](?<key2>.*?)\\[/(?<key3>.*?)\\]", RegexOptions.None).Match(TmpString);
while (mc.Success)
{
if (mc.Groups["key"].Value == mc.Groups["key3"].Value)
{
TmpString = TmpString.Replace(
mc.Groups[0].Value,
GetTagContent(string.Format("[{0}]{1}[/{0}]", mc.Groups["key"].Value, mc.Groups["key2"].Value))
);
}
mc = mc.NextMatch();
}
return TmpString;
}
示例15: ReplaceSystemSetting
/// <summary>
/// 替换系统参数
/// </summary>
/// <param name="TmpString"></param>
/// <returns></returns>
public string ReplaceSystemSetting(string TmpString)
{
Match mc_sys = new Regex("\\[\\!--sys.(?<key>.*?)--\\]", RegexOptions.None).Match(TmpString);
while (mc_sys.Success)
{
TmpString = Regex.Replace(
TmpString,
string.Format("\\[\\!--sys\\.{0}--\\]", mc_sys.Groups["key"].Value),
GetSysSettingContent(mc_sys.Groups["key"].Value)
);
mc_sys = mc_sys.NextMatch();
}
return TmpString;
}