/// <summary> /// Constructor /// </summary> /// <param name="regex">Regular expression as Regex</param> /// <param name="errorMessage">Error message to show when validation fails</param> public RegularExpressionValidator( Regex regex, string errorMessage) : base(errorMessage) { Expression = regex.ToString(); _regex = regex; }
/// <summary> /// Default implementation. /// Command format is "commandname /parameter:valueWithSpaceAllowed /parameter:valueWithSpaceAllowed" /// Case is ignored /// If command can not be parsed, null is returned. /// </summary> /// <example> /// websearch /s:weather cupertino /take:10 /language:de /// </example> /// <param name="command"></param> /// <returns></returns> public IEnumerable<KeyValuePair<string, object>> Parse(string command) { var seperator1 = _notation == ParserNotation.Windows ? '/' : '-'; var seperator2 = _notation == ParserNotation.Windows ? ':' : '='; // Helppage as default: if (string.IsNullOrWhiteSpace(command)) { command = $"ncommandsystem {seperator1}help{seperator2}true"; } if (_systemCommands.Any(x => x == command?.Trim().Trim(seperator1).ToLower())) { command = $"ncommandsystem {seperator1}{command?.Trim().ToLower()}{seperator2}true"; } // Detect flags (eg ' /enable' -> ' /enable:true') command = command + $" {seperator1}"; while (true) { var result = new Regex($" ({seperator1}[a-z,A-Z]+)[ ]+{seperator1}", RegexOptions.IgnoreCase).Match(command); // , command + ":true /" if (!result.Success) break; command = command.Replace(result.ToString(), result.ToString().TrimEnd(seperator1).TrimEnd() + "{seperator2}true {seperator1}"); } command = command.TrimEnd(seperator1).TrimEnd(); // Parse command return StringCommandUtil.ParseCommand(command, "^[a-z,A-Z]+$", $"({seperator1}[a-z,A-Z]+{seperator2})", new [] { seperator1, seperator2 }, true); }
public static Parser<string> GetRegexParser(Regex expression) { return new Parser<string> { ExpectedInput = expression.ToString(), Func = input => { var trimmedInput = input.TrimStart(); var match = expression.Match(trimmedInput); return match.Success && match.Index == 0 ? new Result<string> { Output = match.Value, Rest = trimmedInput.Substring(match.Index + match.Length) } : new Error<string> { Message = $"Expected match on '{expression.ToString()}', got '{input}'.", Expected = expression.ToString(), Actual = trimmedInput }; } }; }
public static string regexComment(string file) { //第一步先去掉多行注释,然后再去掉单行注释,最后将空格换行进行释删除 Regex singleLineComment = new Regex(@"//(.*)", RegexOptions.Compiled);//换行 Regex multiLineComment = new Regex(@"(?<!/)/\*([^*/]|\*(?!/)|/(?<!\*))*((?=\*/))(\*/)", RegexOptions.Compiled | RegexOptions.Multiline); Regex htmlComment = new Regex(@"(<!--)(.+)(-->)",RegexOptions.Compiled|RegexOptions.Multiline); Regex jspComment = new Regex(@"(<%--)(.+)(--%>)",RegexOptions.Multiline); string s = ""; using (StreamReader sr=new StreamReader (file,Encoding.UTF8)) { //替换多行注释 s = sr.ReadToEnd(); s = Regex.Replace(s, multiLineComment.ToString(), ""); s = Regex.Replace(s,singleLineComment.ToString(),""); s = Regex.Replace(s, htmlComment.ToString(), ""); s = Regex.Replace(s, jspComment.ToString(), ""); s=s.Replace(" ", ""); s=s.Replace("\n",""); s = s.Replace("\r", ""); } return s; }
public void AssertOutput(Regex regex) { var allOutput = string.Join(Environment.NewLine, captured.Infos); Assert.That(regex.IsMatch(allOutput), string.Format("Output did not match: {0}. Output:\r\n{1}", regex.ToString(), allOutput) ); }
public void AddToQueue(string source, string destination) { // Detect if the file has already been added with the same destination. if (queue.FirstOrDefault(f => f.FileToExtract == source && f.Destination == destination) != null) { return; } // Detect rar archives named *.part01.rar, *.part02.rar etc. Regex regexPartRar = new Regex(@"part\d*.rar$", RegexOptions.IgnoreCase); Match matchPartRar = regexPartRar.Match(source); if (matchPartRar.Success) { string baseName = source.Substring(0, source.LastIndexOf(matchPartRar.Value)); regexPartRar = new Regex(baseName.Replace("\\", "\\\\") + regexPartRar.ToString(), RegexOptions.IgnoreCase); IEnumerable<QueueItem> items = GetItems().Where(i => regexPartRar.Match(i.FileToExtract.ToLower()).Success).ToList(); if (items.FirstOrDefault(f => f.Destination == destination) != null) { return; } } QueueItem item = new QueueItem() { FileToExtract = source, Destination = destination, ArchiveSize = GetArchiveSize(source) }; queue.Add(item); totalSize += item.ArchiveSize; OnStatusChanged(new ItemAdded(item, queue.Count)); }
private void WriteBson(BsonWriter writer, Regex regex) { // Regular expression - The first cstring is the regex pattern, the second // is the regex options string. Options are identified by characters, which // must be stored in alphabetical order. Valid options are 'i' for case // insensitive matching, 'm' for multiline matching, 'x' for verbose mode, // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode. string options = null; if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) options += "i"; if (HasFlag(regex.Options, RegexOptions.Multiline)) options += "m"; if (HasFlag(regex.Options, RegexOptions.Singleline)) options += "s"; options += "u"; if (HasFlag(regex.Options, RegexOptions.ExplicitCapture)) options += "x"; writer.WriteRegex(regex.ToString(), options); }
public void DeserializesARegex() { var regex = new Regex("its over (\\d+?)", RegexOptions.Multiline | RegexOptions.IgnoreCase); var input = Serializer.Serialize(new { Regex = regex }); var o = Deserializer.Deserialize<Fatty>(input); Assert.Equal(regex.ToString(), o.Regex.ToString()); Assert.Equal(regex.Options, o.Regex.Options); }
private string SerializeRegex(Regex regex) { switch (this.RegexFormat) { case Json.RegexFormat.Create: { StringBuilder flags = new StringBuilder(2); if (regex.Options.HasFlag(RegexOptions.IgnoreCase) == true) { flags.Append("i"); } if (regex.Options.HasFlag(RegexOptions.Multiline) == true) { flags.Append("m"); } if (flags.Length > 0) { return "new RegExp(\"" + regex.ToString() + "\",\"" + flags.ToString() + "\")"; } else { return "new RegExp(\"" + regex.ToString() + "\")"; } } case Json.RegexFormat.Default: { StringBuilder sb = new StringBuilder("/"); sb.Append(regex.ToString()); sb.Append("/"); if (regex.Options.HasFlag(RegexOptions.IgnoreCase) == true) { sb.Append("i"); } if (regex.Options.HasFlag(RegexOptions.Multiline) == true) { sb.Append("m"); } return sb.ToString(); } default: { throw new InvalidEnumArgumentException("JsonHelper.RegexFormat", (int)this.RegexFormat, typeof(Json.RegexFormat)); } } }
private void WriteJson(JsonWriter writer, Regex regex) { writer.WriteStartObject(); writer.WritePropertyName("Pattern"); writer.WriteValue(regex.ToString()); writer.WritePropertyName("Options"); writer.WriteValue(regex.Options); writer.WriteEndObject(); }
public Instruction(string code) { var catchMatch= new Regex("catch start: ([0-9]+);"); var pcMatch = new Regex("^[0-9]+").Match(code);//.ToString(); if(pcMatch.Success) { pc = Convert.ToInt32(pcMatch.ToString()); instArgs = code.Replace(pcMatch.ToString()+".","").Split(null).ToList(); instArgs.RemoveAll(str => String.IsNullOrEmpty(str)); }else { // for exceptions MatchCollection matches = catchMatch.Matches(code); instArgs.Add("catch"); instArgs.Add(matches[0].Groups[1].Value); } }
static int ToString(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 1); System.Text.RegularExpressions.Regex obj = (System.Text.RegularExpressions.Regex)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.Text.RegularExpressions.Regex"); string o = obj.ToString(); LuaScriptMgr.Push(L, o); return(1); }
public VerbalExpressions Add(string value) { _source = _source != null ? _source + value : value; if (_source != null) { p = new Regex(_prefixes + _source + _suffixes, RegexOptions.Multiline); _pattern = p.ToString(); } return this; }
public void WithRegexValueAddsAttributeCorrectly() { Regex value = new Regex( "Regex" ); HtmlAttributeBuilder builder = new HtmlAttributeBuilder(); var result = builder.Pattern( value ); Assert.AreSame( builder, result ); Assert.AreEqual( value.ToString(), builder.Attributes[ HtmlAttributes.Pattern ] ); }
/// <summary> /// Convert a .NET regex into an equivalent symbolic regex /// </summary> /// <param name="regex">the given .NET regex</param> /// <param name="keepAnchors">if false (default) then anchors are replaced by equivalent regexes</param> public SymbolicRegexNode <S> ConvertToSymbolicRegex(System.Text.RegularExpressions.Regex regex, bool keepAnchors = false, bool unwindlowerbounds = false) { var node = ConvertToSymbolicRegex(regex.ToString(), regex.Options, keepAnchors); if (unwindlowerbounds) { node = node.Simplify(); } return(node); }
public void CreateHeaderSeparator_TrueRegex_ReturnTrueRegex() { //Arrange var expected = new Regex("^$"); //Act var actual = MethodTestHelper.RunInstanceMethod<DbRecorderBase, Regex>("CreateHeaderSeparator", _dbRecorderBase, new object[] { }); //Assert Assert.AreEqual(actual.ToString(), expected.ToString()); }
public void CreateFieldSeparator_IfRegexIsWrong_Return() { //Arrange var expected = new Regex(@"^([^\s]+)\s*$"); //Act var actual = MethodTestHelper.RunInstanceMethod<PaloAltoUrlUnifiedRecorder, Regex>("CreateFieldSeparator", _paloAltoUrlUnifiedRecorder, new object[] { }); //Assert Assert.AreNotEqual(actual.ToString(), expected.ToString()); }
public string GetGalleryTitle(string xmlDescription) { Regex regexObj = new Regex("<a[^>]*? href=\"(?<url>[^\"]+)\"[^>]*?>(?<text>.*?)</a>", RegexOptions.Singleline); var match = Regex.Match(xmlDescription, regexObj.ToString()); // get url within the description // match.Groups["url"].Value; return match.Groups["text"].Value; }
private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer) { DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; writer.WriteStartObject(); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName); writer.WriteValue(regex.ToString()); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(OptionsName) : OptionsName); serializer.Serialize(writer, regex.Options); writer.WriteEndObject(); }
/// <summary> /// Registers a new mapping between a regular expression and a value generator. /// </summary> /// <param name="regex">The regular expression to find out a variable.</param> /// <param name="procedure">The value generator.</param> /// <param name="item">The autocomplete item.</param> public void RegisterVariable(Regex regex, Func<Match, object> procedure, RegexAutoCompleteItem item) { if (regex == null) throw new ArgumentNullException("regex"); if (procedure == null) throw new ArgumentNullException("procedure"); if (item == null) throw new ArgumentNullException("item"); Logger.Verbose("Registered the specified pattern '{0}'.", regex.ToString()); evaluators[regex] = procedure; Register(item); }
internal static void FindRegex(TextBoxBase textBox, Regex regex) { Match match = regex.Match(textBox.Text, textBox.SelectionLength == 0 ? textBox.SelectionStart : textBox.SelectionStart + textBox.SelectionLength); if (!match.Success) { WikiPad.FindForm.ShowFormattedMessageBox("No further occurences of RegularExpression \"{0}\" have been found.", regex.ToString()); return; } textBox.SelectionStart = match.Index; textBox.SelectionLength = match.Length; textBox.ScrollToCaret(); }
public void CreateFieldSeparator_IfRegexIsTrue_ReturnRegex() { //Arrange var expected = new Regex("^(?<TIME>[^|]+)\\|\\|(?<EVENT_TYPE>()|([^|]+))\\|\\|(?<EVENT>()|([^|]+))\\|\\|(?<EVENT_ROOT>()|([^|]+))\\|\\|(?<EXE_NAME>()|[^\\\\]+)(()|\\\\)(?<EXE_PATH>()|([^|]+))\\|\\|(?<DOMAIN>[^\\\\]+)(()|\\\\)(?<USER_NAME>()|([^|]+))\\|\\|(?<DEVICE>()|([^|]+))\\|\\|((?<PARTITION>()|([^\\\\]+))(()|\\\\)?(?<FILE_NAME>()|[^\\|]+))\\|\\|(?<HASH>([^|]+))$"); //Act var actual = MethodTestHelper.RunInstanceMethod<NatekAccessControlUnifiedRecorder, Regex>("CreateFieldSeparator", _natekAccessControlUnifiedRecorder, new object[] { }); //Assert Assert.AreEqual(actual.ToString(), expected.ToString()); }
public static List<ArticleType> YahooList(string category) { var itemList = new List<ArticleType>(); try { WebRequest request = WebRequest.Create("http://news.yahoo.com/rss/" + category); WebResponse response = request.GetResponse(); StringBuilder sb = new StringBuilder(""); Stream rssStream = response.GetResponseStream(); XmlDocument rssDoc = new XmlDocument(); rssDoc.Load(rssStream); XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item"); for (int i = 0; i < rssItems.Count; i++) { var tempItem = new ArticleType(); //tempItem.isMain = (i == 0); if (rssItems[i]["media:content"] != null) { var imageUrl = rssItems[i]["media:content"].Attributes[0].InnerText; tempItem.imageUrl = imageUrl;//(tempItem.isMain) ? String.Concat("http", Regex.Split(imageUrl, "http")[2]) : imageUrl; } tempItem.heading = HttpUtility.HtmlDecode(rssItems[i]["title"].InnerText); tempItem.link = rssItems[i]["link"].InnerText; tempItem.content = HttpUtility.HtmlDecode(rssItems[i]["description"].InnerText); tempItem.source = (rssItems[i]["source"] != null) ? String.Concat("Source : ", HttpUtility.HtmlDecode(rssItems[i]["source"].InnerText)) : String.Empty; if (!String.IsNullOrEmpty(rssItems[i]["pubDate"].InnerText)) { var pubDate = DateTime.Now.Subtract(DateTime.Parse(rssItems[i]["pubDate"].InnerText)).ToString(); tempItem.pubDate = Helpers.PublishDateTime(pubDate); } Regex regex = new Regex(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline); tempItem.content = Regex.Replace(tempItem.content, regex.ToString(), String.Empty); if (Validators.ValidateArticle(tempItem)) { itemList.Add(tempItem); } } } catch (Exception) { //throw; } return itemList; }
/// <summary> /// Default implementation. /// Command format is "commandname /parameter:valueWithSpaceAllowed /parameter:valueWithSpaceAllowed" /// Case is ignored /// If command can not be parsed, null is returned. /// </summary> /// <example> /// websearch /s:weather cupertino /take:10 /language:de /// </example> /// <param name="command"></param> /// <returns></returns> public IEnumerable<KeyValuePair<string, object>> Parse(string command) { // Helppage as default: if (string.IsNullOrWhiteSpace(command) || command.Trim().ToLower().StartsWith("/help")) { command = "ncommandsystem /help:true"; } // Detect flags (eg ' /enable' -> ' /enable:true') command = command + " /"; while (true) { var result = new Regex(" (/[a-z,A-Z]+)[ ]+/", RegexOptions.IgnoreCase).Match(command); // , command + ":true /" if (!result.Success) break; command = command.Replace(result.ToString(), result.ToString().TrimEnd('/').TrimEnd() + ":true /"); } command = command.TrimEnd('/').TrimEnd(); // Parse command return StringCommandUtil.ParseCommand(command, "^[a-z,A-Z]+$", "(/[a-z,A-Z]+:)", new [] { '/', ':' }, true); }
public void CreateFieldSeparator_IfRegexIsTrue_ReturnRegex() { //Arrange var expected = new Regex(@"^(?<DOMAIN>[^,]*),(?<RECEIVE_TIME>[^,]*),(?<SERIAL>[^,]*),(?<TYPE>[^,]*),(?<CONTENT_TYPE>[^,]*),(?<CONFIG_VERSION>[^,]*),(?<GENERATE_TIME>[^,]*),(?<SOURCE_ADDRESS>[^,]*),(?<DESTINATION_ADDRESS>[^,]*),(?<NAT_SOURCE_IP>[^,]*),(?<NAT_DESTINATION_IP>[^,]*),(?<RULE>[^,]*),(?<SOURCE_USER>[^,]*),(?<DESTINATION_USER>[^,]*),(?<APPLICATION>[^,]*),(?<VIRTUAL_SYSTEM>[^,]*),(?<SOURCE_ZONE>[^,]*),(?<DESTINATION_ZONE>[^,]*),(?<INBOUND_INTERFACE>[^,]*),(?<OUTBOUND_INTERFACE>[^,]*),(?<LOG_ACTION>[^,]*),(?<TIME_LOGGED>[^,]*),(?<SESSION_ID>[^,]*),(?<REPEAT_COUNT>[^,]*),(?<SOURCE_PORT>[^,]*),(?<DESTINATION_PORT>[^,]*),(?<NAT_SOURCE_PORT>[^,]*),(?<NAT_DESTINATION_PORT>[^,]*),(?<FLAGS>[^,]*),(?<IP_PROTOCOL>[^,]*),(?<ACTION>[^,]*),(((?<BYTES>[^,]*),(?<BYTES_RCV>[^,]*),(?<BYTES_SEND>[^,]*),(?<PACKETS>[^,]*),(?<START_TIME>[^,]*),(?<ELAPSED>[^,]*),(?<URL_CATEGORY>[^,]*),(?<PADDING>[^\,]*))|((?<URL>[^,]*),(?<CONTENT_NAME>[^,]*),(?<CATEGORY>[^,]*),(?<SEVERITY>[^,]*),(?<DIRECTION>[^\,]*)))$"); //Act var actual = MethodTestHelper.RunInstanceMethod<PaloAltoUrlUnifiedRecorder, Regex>("CreateFieldSeparator", _paloAltoUrlUnifiedRecorder, new object[] { }); //Assert Assert.AreEqual(actual.ToString(), expected.ToString()); }
static new public int ToString(IntPtr l) { try { System.Text.RegularExpressions.Regex self = (System.Text.RegularExpressions.Regex)checkSelf(l); var ret = self.ToString(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static void Main() { try { TradeFunctions goxClient = new TradeFunctions(); Console.Write ( Environment.NewLine + " 1. GetTicker" + Environment.NewLine + " 2. GetDepth" + Environment.NewLine + " 3. GetCurrency" + Environment.NewLine + " 4. GetInfo" + Environment.NewLine + " 5. GetIdKey" + Environment.NewLine + " 6. GetOrders" + Environment.NewLine + Environment.NewLine + "Choose a Trade Function: " ); string userEntry = Console.ReadLine(); if(string.IsNullOrEmpty(userEntry)) throw new Exception("You must make an entry!"); Match tradeFunction = new Regex(@"[0-9]").Match(userEntry); if (!tradeFunction.Success) throw new Exception("You must enter a number!"); switch (tradeFunction.ToString()) { case "1": Console.WriteLine(Environment.NewLine + goxClient.GetTicker(Currency.USD).ToString()); break; case "2": Console.WriteLine(Environment.NewLine + goxClient.GetOrders().ToString()); break; case "3": break; case "4": break; case "5": break; case "6": break; } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } }
public void RegisterSymbol(string symbolName) { var rg = new Regex(symbolName); foreach (var token in m_Tokens) { if (token.TokenType == TokenType.Symbol) { if (token.Regex.ToString() == rg.ToString()) return; } } m_Tokens.Add(new Token(rg, TokenType.Symbol, OperationType.Operand)); }
public bool GetFileList(string url, Regex filter, out string[] files) { ArrayList fs = new ArrayList(); FtpWebRequest r = null; FtpWebResponse wr = null; try { r = (FtpWebRequest)FtpWebRequest.Create(url); r.KeepAlive = false; r.Method = WebRequestMethods.Ftp.ListDirectory; r.Credentials = new NetworkCredential(user, password); r.UseBinary = true; Log.Inform(r.Method + ":" + r.RequestUri.ToString()); wr = (FtpWebResponse)r.GetResponse(); System.IO.Stream stream = wr.GetResponseStream(); StreamReader sr = new StreamReader(stream); if (filter != null) filter = new Regex(filter.ToString(), filter.Options | RegexOptions.Compiled); string dirorfile = null; while ((dirorfile = sr.ReadLine()) != null) { if (filter != null && !filter.IsMatch(dirorfile)) continue; fs.Add(dirorfile); } files = (string[])fs.ToArray(typeof(string)); return true; } catch (Exception e) { Log.Error(e); } finally { try { if (wr != null) wr.Close(); //if (ftp != null) // ftp.Abort(); } catch { }; } files = null; return false; }
private void WriteBson(BsonWriter writer, Regex regex) { string str = (string) null; if (this.HasFlag(regex.Options, RegexOptions.IgnoreCase)) str = str + "i"; if (this.HasFlag(regex.Options, RegexOptions.Multiline)) str = str + "m"; if (this.HasFlag(regex.Options, RegexOptions.Singleline)) str = str + "s"; string options = str + "u"; if (this.HasFlag(regex.Options, RegexOptions.ExplicitCapture)) options = options + "x"; writer.WriteRegex(regex.ToString(), options); }
public void SetParameters(ConfigParameters parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } var filters = from f in parameters.Keys let e = Escape(f) select e; filter = new Regex( string.Join("|", filters), RegexOptions.Compiled | RegexOptions.IgnoreCase ); NoticeFormat("Using filter {0}", filter.ToString()); }
internal void RewriteInboundLinks(string fileToContextualize, IEnumerable<IndexEntry> allFiles) { string fileLinkShortName = fileToContextualize.Substring(fileToContextualize.LastIndexOf(@"\") + 1); Regex contextPattern = new Regex(@"virtual-machines-linux-classic-.+?\.md(?=\?toc=)"); Regex noContextPattern = new Regex(fileLinkShortName + @"\)"); foreach (IndexEntry fileToExamine in allFiles) { string fileTextToExamine = File.ReadAllText(this.repo.Info.WorkingDirectory + Path.DirectorySeparatorChar + fileToExamine.Path); if (fileTextToExamine == string.Empty) { throw new Exception(this.repo.Info.WorkingDirectory + Path.DirectorySeparatorChar + fileToExamine.Path); } if (Regex.IsMatch(fileTextToExamine, noContextPattern.ToString())) { var results = Regex.Replace(fileTextToExamine, noContextPattern.ToString(), fileLinkShortName + @"?toc=%2fazure%2fvirtual-machines%2flinux%2fclassic%2ftoc.json)"); File.WriteAllText(this.repo.Info.WorkingDirectory + fileToExamine.Path, results); Console.WriteLine("match rewritten"); } else Console.WriteLine("no match"); } }
public static Match FindMatches(Regex matchstring, string filename) { var text = File.ReadAllText(filename); Match result; if (string.IsNullOrEmpty(matchstring.ToString())) { result = null; } else { var match = matchstring.Match(text.ToLower()); result = match; } return result; }
internal bool Match(MailItem item, ref RegexResults results) { Match match = null; switch (scope) { case Scope.subject: match = realRegex.Match(item.Subject); break; case Scope.body: match = realRegex.Match(item.Body); break; case Scope.from: match = realRegex.Match(item.SenderName); break; case Scope.to: match = realRegex.Match(item.To); break; case Scope.cc: match = realRegex.Match(item.CC); break; default: return(false); } if (!match.Success) { return(false); } Globals.ThisAddIn.GetLogger().Log($"{scope.ToString()} - {realRegex.ToString()}"); for (int i = 0; i < match.Groups.Count; ++i) { Globals.ThisAddIn.GetLogger().Log($"{i}. {match.Groups[i].Value}"); } results.Append(match, scope); return(true); }
public override string ToString() { return(_regex.ToString()); }
public static NotationTrack parseMidiTrack(Midi.Track track, int division, ref Regex fingerPattern) { int microsecondsPerBeat = Midi.PpqnClock.DefaultTempo; float time = 0; TrackStatus trackStatus = new TrackStatus(); FingerChordMap fingerMap = new FingerChordMap(); List <Note> notes = new List <Note>(); Regex fingerMetaPattern = new Regex("fingering-marker-pattern:(.*)"); string name = ""; foreach (Midi.MidiEvent e in track.Iterator()) { time += e.DeltaTicks * microsecondsPerBeat / (division * 1000); switch (e.MidiMessage.MessageType) { case Midi.MessageType.Meta: Midi.MetaMessage mm = e.MidiMessage as Midi.MetaMessage; switch (mm.MetaType) { case Midi.MetaType.Tempo: Midi.TempoChangeBuilder builder = new Midi.TempoChangeBuilder(mm); microsecondsPerBeat = builder.Tempo; break; case Midi.MetaType.Text: { string text = Encoding.Default.GetString(mm.GetBytes()); var match = fingerMetaPattern.Match(text); if (match.Success) { fingerPattern = new Regex(match.Groups[1].ToString()); Debug.LogFormat("Finger Pattern found: {0}", fingerPattern.ToString()); } } break; case Midi.MetaType.Marker: if (fingerPattern != null) { string text = Encoding.Default.GetString(mm.GetBytes()); var match = fingerPattern.Match(text); if (match.Success) { //Debug.LogFormat("Finger: {0}", text); try { int pitch = int.Parse(match.Groups[1].ToString()); Finger finger = (Finger)int.Parse(match.Groups[2].ToString()); if (!fingerMap.ContainsKey(e.AbsoluteTicks)) { fingerMap[e.AbsoluteTicks] = new FingerChord(); } fingerMap[e.AbsoluteTicks][pitch] = finger; } catch (System.Exception except) { Debug.LogWarningFormat("fingering marker parse failed: {0}, {1}", text, except.Message); } } //else // Debug.LogWarningFormat("fail marker: {0}", text); } break; case Midi.MetaType.TrackName: name = Encoding.Default.GetString(mm.GetBytes()); break; } break; case Midi.MessageType.Channel: Midi.ChannelMessage cm = e.MidiMessage as Midi.ChannelMessage; if (!trackStatus.ContainsKey(cm.MidiChannel)) { trackStatus[cm.MidiChannel] = new ChannelStatus(); } var commandType = cm.Command; if (commandType == Midi.ChannelCommand.NoteOn && cm.Data2 == 0) { commandType = Midi.ChannelCommand.NoteOff; } switch (commandType) { case Midi.ChannelCommand.NoteOn: { int pitch = cm.Data1; int velocity = cm.Data2; if (pitch >= Piano.PitchMin && pitch <= Piano.PitchMax) { trackStatus[cm.MidiChannel][pitch] = new PitchStatus { tick = e.AbsoluteTicks, startTime = time, velocity = velocity } } ; } break; case Midi.ChannelCommand.NoteOff: { int pitch = cm.Data1; if (!trackStatus[cm.MidiChannel].ContainsKey(pitch)) { Debug.LogWarningFormat("Unexpected noteOff: {0}, {1}", e.AbsoluteTicks, pitch); } else { PitchStatus status = trackStatus[cm.MidiChannel][pitch]; Note note = new Note { tick = status.tick, start = status.startTime, duration = time - status.startTime, pitch = pitch, velocity = status.velocity }; if (fingerMap.ContainsKey(note.tick) && fingerMap[note.tick].ContainsKey(note.pitch)) { note.finger = fingerMap[note.tick][note.pitch]; } notes.Add(note); } } break; } break; } } NotationTrack notation = new NotationTrack(); notation.notes = notes.ToArray(); notation.name = name; return(notation); }