本文整理汇总了C#中System.Text.RegularExpressions.Regex类的典型用法代码示例。如果您正苦于以下问题:C# Regex类的具体用法?C# Regex怎么用?C# Regex使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Regex类属于System.Text.RegularExpressions命名空间,在下文中一共展示了Regex类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ShouldRegexMatchColonTerminatedFirstMultilineSlashNTerminated
public void ShouldRegexMatchColonTerminatedFirstMultilineSlashNTerminated()
{
string content = string.Format("blah:{0}blah", "\n");
Regex regex = new Regex(".*:$", RegexOptions.Multiline);
regex.IsMatch(content).Should().BeTrue();
regex.Matches(content).Count.Should().Be(1);
}
示例2: MessInfo
public MessInfo(string s)
{
const string FILE = "file";
const string LINE = "line";
const string COND = "cond";
const string ERROR = "error";
const string MESSAGE = "message";
Regex rex = new Regex(@"""?(?<" + FILE + @">[a-zA-Z]:\\(?:[^\\/:*?<>|\r\n]+\\)*(?:[^\\/:*?""<>|\r\n]+))""?,\sline\s(?<" + LINE + @">[0-9]+):\s(?<" + COND + @">Error|Warning):[^#]+#(?<"[email protected]">[0-9]+(?:-\D)?):\s*(?<"[email protected]">.+)\z");
Match m = rex.Match(s);
if (m.Success)
{
try
{
this.File = m.Groups[FILE].Value;
this.Line = int.Parse(m.Groups[LINE].Value);
this.Cond = (Level)Enum.Parse(typeof(Level), m.Groups[COND].Value);
this.Error = m.Groups[ERROR].Value;
this.Message = m.Groups[MESSAGE].Value;
this.Success = true;
}
catch
{
this.Success = false;
}
}
}
示例3: CorrectUrl
/// <summary>
/// Corrects the image path relative to the requested page or css where they originate from
/// </summary>
/// <param name="url"></param>
/// <param name="requestPath"></param>
/// <returns></returns>
public static string CorrectUrl(string url, string requestPath)
{
var correctedImgPath = url.TrimStart('~');
// make sure 'requestPath' starts with a '/'
if (!requestPath.StartsWith("/"))
requestPath = "/" + requestPath;
if (!url.StartsWith("/") && !url.StartsWith("../"))
{
correctedImgPath = VirtualPathUtility.GetDirectory(requestPath) + url.TrimStart('/');
}
else if (url.StartsWith("../"))
{
var path = VirtualPathUtility.GetDirectory(requestPath);
var regex = new Regex(@"\.\./");
var levelUpMatches = regex.Matches(url);
var numberOfLevelsUp = levelUpMatches.Count;
var pathDirs = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var newPathDirs = pathDirs.Take(pathDirs.Length - numberOfLevelsUp);
var newPath = String.Join("/", newPathDirs).Trim();
correctedImgPath = regex.Replace(url, "");
correctedImgPath = String.IsNullOrEmpty(newPath) ? String.Format("/{0}", correctedImgPath) : String.Format("/{0}/{1}", newPath, correctedImgPath);
}
return correctedImgPath;
}
示例4: UpdateStatus
public static string UpdateStatus(string status, TwUser user, string replyId)
{
Regex regex = new Regex(@"\[(.*?)\]");
List<FileInfo> media = new List<FileInfo>();
foreach (System.Text.RegularExpressions.Match match in regex.Matches(status))
{
status = status.Replace(match.Value, "");
FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", ""));
if (!file.Exists)
throw new FileNotFoundException("File not found", file.FullName);
media.Add(file);
}
if (media.Count > 4) //limited by the twitter API
throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet");
if (user == null)
user = TwUser.LoadCredentials();
string encodedStatus = Util.EncodeString(status);
if (media.Count == 0)
return InternalUpdateStatus(user, encodedStatus, replyId);
else
return InternalUpdateWithMedia(user, encodedStatus, replyId, media);
}
示例5: getInnerHTML
/// <summary>
/// Gets inner HTML string from the first found element with the given class name (e.g. class="sample-test").
/// </summary>
/// <param name="sourceString">An HTML string to parse.</param>
/// <param name="className">Class name.</param>
/// <returns>An HTML string.</returns>
public static string getInnerHTML(string sourceString, string className)
{
Match match = new Regex(className).Match(sourceString);
if (!match.Success) return "";
int lb = match.Index + className.Length;
for (; lb < sourceString.Length && !(sourceString[lb - 1] == '>' && sourceString[lb - 2] != '\\'); lb++);
int rb = lb, tmp, bracketCounter = 1;
while (bracketCounter > 0)
{
while (rb < sourceString.Length && !(sourceString[rb] == '<' && sourceString[rb - 1] != '\\')) rb++;
tmp = rb + 1;
while (tmp < sourceString.Length && !(sourceString[tmp] == '>' && sourceString[tmp - 1] != '\\')) tmp++;
if (sourceString[rb + 1] == '/') bracketCounter--;
else if (sourceString[tmp - 1] != '/') bracketCounter++;
rb++;
}
while (!(sourceString[--rb] == '<' && sourceString[rb - 1] != '\\')) ;
return sourceString.Substring(lb, rb - lb);
}
示例6: DataSet
public override void DataSet(string myPath, string myPattern)
{
string[] fileList = Directory.GetFiles(myPath, myPattern, SearchOption.AllDirectories);
Regex regexMov = new Regex(MovieContents.REGEX_MOVIE_EXTENTION, RegexOptions.IgnoreCase);
Regex regexJpg = new Regex(@".*\.jpg$|.*\.jpeg$", RegexOptions.IgnoreCase);
Regex regexLst = new Regex(@".*\.wpl$|.*\.asx$", RegexOptions.IgnoreCase);
foreach (string file in fileList)
{
listFileInfo.Add(new common.FileContents(file, myPath));
if (regexMov.IsMatch(file))
MovieCount++;
if (regexJpg.IsMatch(file))
ImageCount++;
if (regexLst.IsMatch(file))
ListCount++;
if (regexJpg.IsMatch(file) && ImageCount == 1)
StartImagePathname = file;
}
ColViewListFileInfo = CollectionViewSource.GetDefaultView(listFileInfo);
if (ColViewListFileInfo != null && ColViewListFileInfo.CanSort == true)
{
ColViewListFileInfo.SortDescriptions.Clear();
ColViewListFileInfo.SortDescriptions.Add(new SortDescription("FileInfo.LastWriteTime", ListSortDirection.Ascending));
}
}
示例7: ValidateInputText
private void ValidateInputText()
{
if (regexPattern == String.Empty)
{
Message = "Regex is Empty";
return;
}
try
{
regex = new Regex(regexPattern);
Message = String.Empty;
}
catch (ArgumentException error)
{
Message = error.Message;
return;
}
if (InputText != null)
{
bool isMatch = regex.IsMatch(InputText);
if (isMatch)
{
Message = "It's works!";
}
else
{
Message = "No working :(";
}
}
}
示例8: 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);
}
示例9: ExecuteMethodFromRegex
public void ExecuteMethodFromRegex(IrcEventArgs e)
{
if(isRunning==true)
{
SendUnscramble(e);
}
foreach(KeyValuePair<string,string> pair in regexDictionary)
{
regex = new Regex(pair.Key);
if(regex.IsMatch(e.Data.Message))
{
string methodName = pair.Value;
//Get the method information using the method info class
MethodInfo mi = this.GetType().GetMethod(methodName);
object[] objargs = new object[1];
objargs[0]=e;
// //Invoke the method
// // (null- no paramyeseter for the method call
// // or you can pass the array of parameters...)
if(mi==null)
{
//client.SendMessage(SendType.Message, e.Data.Channel,"mi is null! "+e.Data.Message);
SharpBotClient.SharpBotClient.SendChannelMessag(e.Data.Channel,"handled from client");
}
else
{
mi.Invoke(this,objargs);
}
}
}
}
示例10: Process
/// <summary>
/// Обрабатывает шаблон, вставляет значение полей моделей в макросы в шаблоне
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
protected override string Process(string content)
{
// Подгатавливаем данные
var parseRegEx = new Regex(@"\$\{([A-Za-z0-9]+?)\}");
var sb = new StringBuilder(content);
var ti = Model.GetType();
// Находим все вхождения макросов по регулярному выражению
var matches = parseRegEx.Matches(content);
foreach (Match match in matches)
{
var propertyName = match.Groups[1].Value;
// Ищем свойство у модели
var propertyInfo = ti.GetProperty(propertyName);
if (propertyInfo == null)
{
// Похоже что данное свойство у модели не найдено
continue;
}
var value = propertyInfo.GetValue(Model,null);
// Выполняем замену
sb.Replace(match.Value, value != null ? value.ToString() : String.Empty);
}
// Отдаем преобразованный результат
return sb.ToString();
}
示例11: RowCount
public int RowCount(string source)
{
Regex rowRegex = new Regex(_rowDelimiter);
_source = source;
_rows = rowRegex.Matches(_source);
return _rows.Count;
}
示例12: GetMatchingVertices
public override IEnumerable<IVertex> GetMatchingVertices(IVertexType myInterestingVertexType)
{
Regex regexpression;
try
{
regexpression = new Regex((String)_constant.Value);
}
catch (Exception e)
{
throw new InvalidLikeOperationException(String.Format("Invalid regular expression given:{0}{1}", Environment.NewLine, e.Message), e);
}
foreach (var aVertex in _vertexStore.GetVerticesByTypeID(_securityToken, _transactionToken, myInterestingVertexType.ID, _property.Edition, VertexRevisionFilter))
{
var value = _property.Property.GetValue(aVertex);
if (value != null && (regexpression.IsMatch((String)value)))
{
yield return aVertex;
}
}
yield break;
}
示例13: LoadProjects
private IEnumerable<string> LoadProjects(
string solutionPath)
{
const string projectRegEx = "Project\\(\"\\{[\\w-]*\\}\"\\) = \"([\\w _]*.*)\", \"(.*\\.(cs|vcx|vb)proj)\"";
var content = File.ReadAllText(solutionPath);
var projReg = new Regex(projectRegEx, RegexOptions.Compiled);
var matches = projReg.Matches(content).Cast<Match>();
var projects = matches.Select(x => x.Groups[2].Value).ToList();
for (var i = 0; i < projects.Count; ++i)
{
if (!Path.IsPathRooted(projects[i]))
{
var folderName = Path.GetDirectoryName(solutionPath);
if (folderName != null)
projects[i] = Path.Combine(folderName, projects[i]);
}
try
{
projects[i] = Path.GetFullPath(projects[i]);
}
catch (NotSupportedException ex)
{
resolver_ProgressMessageEvent($"Path: {projects[i]}, Error: {ex.Message}");
}
}
return projects;
}
示例14: CheckMetaCharSetAndReEncode
private string CheckMetaCharSetAndReEncode(Stream memStream, string html)
{
Match m = new Regex(@"<meta\s+.*?charset\s*=\s*(?<charset>[A-Za-z0-9_-]+)", RegexOptions.Singleline | RegexOptions.IgnoreCase).Match(html);
if (m.Success)
{
string charset = m.Groups["charset"].Value.ToLower() ?? "iso-8859-1";
if ((charset == "unicode") || (charset == "utf-16"))
{
charset = "utf-8";
}
try
{
Encoding metaEncoding = Encoding.GetEncoding(charset);
if (Encoding != metaEncoding)
{
memStream.Position = 0L;
StreamReader recodeReader = new StreamReader(memStream, metaEncoding);
html = recodeReader.ReadToEnd().Trim();
recodeReader.Close();
}
}
catch (ArgumentException)
{
}
}
return html;
}
示例15: TypePattern
public TypePattern()
{
IPattern descritePattern = PatternFactory.GetInstance().Get(typeof (DiscreteTypePattern));
IPattern compositePattern = PatternFactory.GetInstance().Get(typeof (CompositeTypePattern));
m_TextPattern = "(" + descritePattern.TextPattern + "|" + compositePattern.TextPattern + ")";
m_Regex = new Regex(m_TextPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
}