本文整理汇总了C#中System.Text.RegularExpressions.Regex类的典型用法代码示例。如果您正苦于以下问题:C# Regex类的具体用法?C# Regex怎么用?C# Regex使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Regex类属于System.Text.RegularExpressions命名空间,在下文中一共展示了Regex类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
开发者ID:fireball87,项目名称:Telnet,代码行数:7,代码来源:WithClient.cs
示例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;
}
}
}
开发者ID:AlexandrSurkov,项目名称:PKStudio,代码行数:26,代码来源:PKMessParser.cs
示例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;
}
开发者ID:jalva,项目名称:JsAndCssCombiner,代码行数:33,代码来源:ImagePathsUtility.cs
示例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);
}
开发者ID:gitter-badger,项目名称:shelltwit,代码行数:25,代码来源:Update.cs
示例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);
}
开发者ID:KirillNikonov,项目名称:cf-tester-extention,代码行数:33,代码来源:HTMLParser.cs
示例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));
}
}
开发者ID:JuichiHirao,项目名称:wpfMovieManager2,代码行数:30,代码来源:SiteDetail.cs
示例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 :(";
}
}
}
开发者ID:GeekyTheory,项目名称:RegexTester,代码行数:32,代码来源:MainViewModel.cs
示例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);
}
开发者ID:phatnguyen81,项目名称:TinyCms,代码行数:34,代码来源:CodeFormat.cs
示例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);
}
}
}
}
开发者ID:drewlander,项目名称:SharpBot,代码行数:33,代码来源:WordScrambler.cs
示例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();
}
开发者ID:softgears,项目名称:kartel,代码行数:35,代码来源:ParametrizedFileTemplate.cs
示例11: RowCount
public int RowCount(string source)
{
Regex rowRegex = new Regex(_rowDelimiter);
_source = source;
_rows = rowRegex.Matches(_source);
return _rows.Count;
}
开发者ID:arangas,项目名称:MediaPortal-1,代码行数:7,代码来源:DataRows.cs
示例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;
}
开发者ID:anukat2015,项目名称:sones,代码行数:25,代码来源:QueryPlanLikeWithoutIndex.cs
示例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;
}
开发者ID:modulexcite,项目名称:ResolveUR,代码行数:27,代码来源:RemoveUnusedSolutionReferences.cs
示例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;
}
开发者ID:jooooel,项目名称:OpenGraph-Net,代码行数:29,代码来源:HttpDownloader.cs
示例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);
}
开发者ID:smithimage,项目名称:MIMER,代码行数:7,代码来源:TypePattern.cs
示例16: FlexibleFloat
public FlexibleFloat(string value)
{
// Variables
Regex re= new Regex(@"([0-9]+)(px|%||em|ex|ch|rem|vw|cm|mm|inches|pt|pc)");
string[] splits= re.Replace(value.Trim(), "$1 $2").Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
val= float.Parse(splits[0]);
switch(splits[1])
{
case "px": unitType= FlexFloatType.px; break;
case "%": unitType= FlexFloatType.percentage; break;
case "em": unitType= FlexFloatType.em; break;
case "ex": unitType= FlexFloatType.ex; break;
case "ch": unitType= FlexFloatType.ch; break;
case "rem": unitType= FlexFloatType.rem; break;
case "vw": unitType= FlexFloatType.vw; break;
case "vh": unitType= FlexFloatType.vh; break;
case "cm": unitType= FlexFloatType.cm; break;
case "mm": unitType= FlexFloatType.mm; break;
case "inches": unitType= FlexFloatType.inches; break;
case "pt": unitType= FlexFloatType.pt; break;
case "pc": unitType= FlexFloatType.pc; break;
default: unitType= FlexFloatType.px; break;
}
}
开发者ID:pgonzbecer,项目名称:apis-bundle,代码行数:25,代码来源:FlexibleFloat.cs
示例17: TestPromotionForStorage
public void TestPromotionForStorage()
{
string test
= @"integer g() { return 0; }
f() {
integer i;
float f = 1;
float h = g();
float j = i;
float l = i++;
float k = i - 5;
f = 1;
h = g();
j = i;
l = i++;
k = i - 5;
}
default { state_entry() {} }
";
TestListener listener = new TestListener();
MCompilerFrontend testFrontend = new MCompilerFrontend(listener, "..\\..\\..\\..\\grammar", true);
CompiledScript script = testFrontend.Compile(test);
string byteCode = testFrontend.GeneratedByteCode;
Console.WriteLine(byteCode);
int castCount = new Regex("fcast").Matches(byteCode).Count;
Assert.IsTrue(listener.HasErrors() == false);
Assert.AreEqual(castCount, 10);
}
开发者ID:emperorstarfinder,项目名称:phlox,代码行数:33,代码来源:Generator.cs
示例18: GetBoards
public static List<Category> GetBoards(this string url)
{
var temp = new List<Category>();
if (url.Contains("collection"))
{
temp.Add(Category.General);
temp.Add(Category.Manga);
temp.Add(Category.HighRes);
return temp;
}
var board = new Regex("(board=[0-9]{0,3})");
var boardMatch = board.Match(url);
var boards = Regex.Replace(boardMatch.Value, "[^0-9]+", string.Empty);
if (boards.Contains("2"))
temp.Add(Category.General);
if (boards.Contains("1"))
temp.Add(Category.Manga);
if (boards.Contains("3"))
temp.Add(Category.HighRes);
return temp;
}
开发者ID:halalfood,项目名称:WallbaseDownloader,代码行数:25,代码来源:Extensions.cs
示例19: tb_humidity_input_TextChanged
private void tb_humidity_input_TextChanged(object sender, EventArgs e)
{
if(tb_humidity_input.Text != "") {
string pattern = @"^[0-9]*(?:\.[0-9]*)?$";//@"^[0 - 9]([.][0 - 9])?$"; //@"^[0-9]+$"; //for integers only
Regex rgx = new Regex(pattern);
string text = tb_humidity_input.Text;
//string sentence = "Who writes these notes?";
if (rgx.IsMatch(text) == true)
{
//matched no need to edit
double x = double.Parse(tb_humidity_input.Text);
if (x >= 0 && x <= 100)
{
}
else
{
//show error message.
MessageBox.Show("Value out of range");
tb_humidity_input.Text = 0.ToString();
}
}
else
{
MessageBox.Show("You can only input integer values between 0-100%");
// dataGridView1.CurrentCell.Value = initialNodeSize;
tb_humidity_input.Text = 0.ToString();
}
}
else
{
tb_humidity_input.Text = 0.ToString();
}
}
开发者ID:temcocontrols,项目名称:T3000_Building_Automation_System,代码行数:35,代码来源:Form_input_by_temp_hum_for_main.cs
示例20: GetThpp
public static int GetThpp(this string str)
{
var numReg = new Regex("thpp=([0-9]{0,9})");
var numMatch = numReg.Match(str);
return Convert.ToInt32(numMatch.Groups[1].ToString());
}
开发者ID:halalfood,项目名称:WallbaseDownloader,代码行数:7,代码来源:Extensions.cs
注:本文中的System.Text.RegularExpressions.Regex类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论