예제 #1
0
        public void should_match_from_index()
        {
            var re      = new PcreRegex(@"a");
            var matches = re.Matches("foo bar baz", 6).ToList();

            Assert.That(matches, Has.Count.EqualTo(1));
        }
예제 #2
0
        public void should_report_callout_exception_ref()
        {
            var re = new PcreRegex(@"a(?C1)");

            var resultCount = 0;

            Assert.Throws <PcreCalloutException>(() =>
            {
                re.Matches("aaa".AsSpan(), 0, callout =>
                {
                    if (callout.StartOffset >= 2)
                    {
                        throw new InvalidOperationException("Simulated exception");
                    }

                    return(PcreCalloutResult.Pass);
                }).ToList(i =>
                {
                    ++resultCount;
                    return(true);
                });
            });

            Assert.That(resultCount, Is.EqualTo(2));
        }
예제 #3
0
        private static JObject ExtractXml(string text, out string error)
        {
            var result = new JObject
            {
                { EXPENSE, new JObject() },
                { "_original", text }
            };

            foreach (PcreMatch match in ExtractXmlRE.Matches(text
#if PCRE_DEBUG
                                                             , 0, AutoCalloutHandler(text)
#endif
                                                             ))
            {
                ProcessXmlFragment(match.Value, result);
            }

            var    expense = (JObject)result[EXPENSE];
            JToken _;
            var    errors =
                from requiredKey in RequiredKeys
                where !expense.TryGetValue(requiredKey, out _)
                select $"Required key '{requiredKey}' was not found!";

            if (LooseXmlRE.IsMatch(ExtractXmlRE.Replace(text, "")))
            {
                errors = errors.Concat(new[] { "Malformed XML found!" });
            }


            error = string.Join(Environment.NewLine, errors).NullIfEmpty();
            return(result);
        }
예제 #4
0
        /// <summary>
        /// Мапирует релиз сайта album-info в музыкальный релиз
        /// </summary>
        /// <param name="release">Релиз сайта album-info</param>
        /// <returns>Музыкальный релиз</returns>
        private DbMusic MapAlbumInfoReleaseToMusic(AlbumInfoRelease release)
        {
            var music = new DbMusic();

            var releaseName = PcreRegex.Match(release.Name, Helper.ReleaseNamePattern).Value;
            var releaseType = PcreRegex.Matches(release.Name, Helper.ReleaseTypePattern)
                              .Select(m => m.Value).LastOrDefault();
            var releaseArtist = release.Name.Substring(0, release.Name.IndexOf(" - ", StringComparison.Ordinal));
            var releaseGenres = PcreRegex.Matches(release.Genre, Helper.ReleaseGenrePattern).Select(m => m.Value);
            var dateFormat    = release.Date.Length > 4 ? Helper.LongDateFormat : Helper.ShortDateFormat;
            var provider      = CultureInfo.CreateSpecificCulture(Const.CultureInfoText);
            var releaseDate   = DateTime.ParseExact(release.Date, dateFormat, provider);

            SaveMusician(music, releaseArtist);
            SaveGenre(music, releaseGenres);

            music.Title           = string.IsNullOrEmpty(releaseName) ? Helper.UnknownName : releaseName;
            music.ReleaseDate     = releaseDate;
            music.Type            = releaseType;
            music.Artist          = string.IsNullOrEmpty(releaseArtist) ? Helper.UnknownArtist : releaseArtist;
            music.PosterImagePath = release.CoverPath;
            music.PosterImageUrl  = release.ImageFullUrl;

            return(music);
        }
예제 #5
0
        public void should_match_starting_at_end_of_string()
        {
            var re      = new PcreRegex(@"(?<=a)");
            var matches = re.Matches("xxa", 3).ToList();

            Assert.That(matches, Has.Count.EqualTo(1));
        }
예제 #6
0
        public void readme_backtracking_verbs_example()
        {
            var matches = PcreRegex.Matches("(foo) bar (baz) 42", @"\(\w+\)(*SKIP)(*FAIL)|\w+")
                          .Select(m => m.Value)
                          .ToList();

            Assert.That(matches, Is.EqualTo(new[] { "bar", "42" }));
        }
예제 #7
0
        public static Monster getMonsterfromMarkup(string markup)
        {
            var monster  = new Monster();
            var textInfo = new CultureInfo("en-US", false).TextInfo;

            //Regex headersRX = new Regex("^(\\w*):\\s\"?(.*)\"?/gm");


            var headersRGX = PcreRegex.Matches(markup, @"^(\w*):\s\""?([\w\d -\[\]\,\ \/]*)\""?", PcreOptions.MultiLine);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            foreach (var rgx in headersRGX)
            {
                //A valid header
                if (rgx.CaptureCount == 2)
                {
                    headers.Add(rgx[1].ToString(), rgx[2].ToString());
                }
            }

            monster.Name = headers["title"];

            var cr_sourceRGX = PcreRegex.Matches(markup, @"cr(\d\/?\d?),\s+([\w-]+)");

            foreach (var rgx in cr_sourceRGX)
            {
                if (rgx.CaptureCount == 2)
                {
                    monster.Challenge = new Fraction(rgx[1].ToString());
                    monster.Source    = textInfo.ToTitleCase(rgx[2].ToString().Replace('-', ' '));
                }
            }

            var infoRGX = PcreRegex.Matches(markup, @"^\*+(.*?)\*+(.*)", PcreOptions.MultiLine);

            int a = 0;

            List <String> properties = new List <string>();

            foreach (var rgx in infoRGX)
            {
                //First one is the type string
                if (a > 0)
                {
                }
                //switch (a)
                //{

                //}
                a++;
            }



            return(monster);
        }
예제 #8
0
        public static IEnumerable <int[]> AsSeparatedInts(this IInputLines lines)
        {
            var regex = new PcreRegex(@"(\d+)\s?", PcreOptions.Compiled);

            return(lines.Transform(line =>
            {
                var matches = regex.Matches(line);

                return matches.Select(m => int.Parse(m.Value)).ToArray();
            }));
        }
예제 #9
0
        public void should_handle_empty_matches()
        {
            var re      = new PcreRegex(@"(?=(a))");
            var matches = re.Matches("aaabbaa").ToList();

            Assert.That(matches, Has.Count.EqualTo(5));

            Assert.That(matches.Select(m => m.Index), Is.EqualTo(new[] { 0, 1, 2, 5, 6 }));
            Assert.That(matches.Select(m => m.Length), Is.All.EqualTo(0));
            Assert.That(matches.Select(m => m.Value), Is.All.EqualTo(String.Empty));

            Assert.That(matches.Select(m => m[1].Index), Is.EqualTo(new[] { 0, 1, 2, 5, 6 }));
            Assert.That(matches.Select(m => m[1].Length), Is.All.EqualTo(1));
            Assert.That(matches.Select(m => m[1].Value), Is.All.EqualTo("a"));
        }
예제 #10
0
        public IEnumerable <string> MatchesUniq(string input, string pattern)
        {
            var matches = PcreRegex.Matches(input, pattern, PcreOptions.IgnoreCase);

            foreach (var match in matches)
            {
                foreach (var group in match.Groups)
                {
                    if (!match.Value.Equals(group.Value))
                    {
                        yield return(group.Value);
                    }
                }
            }
        }
예제 #11
0
        public void should_handle_empty_matches_ref()
        {
            var re      = new PcreRegex(@"(?=(a))");
            var matches = re.Matches("aaabbaa".AsSpan())
                          .ToList(m => (Value: m.Value.ToString(), m.Index, m.Length, Groups: m.Groups.ToList(g => (Value: g.Value.ToString(), g.Index, g.Length))));

            Assert.That(matches, Has.Count.EqualTo(5));

            Assert.That(matches.Select(m => m.Index), Is.EqualTo(new[] { 0, 1, 2, 5, 6 }));
            Assert.That(matches.Select(m => m.Length), Is.All.EqualTo(0));
            Assert.That(matches.Select(m => m.Value), Is.All.EqualTo(String.Empty));

            Assert.That(matches.Select(m => m.Groups[1].Index), Is.EqualTo(new[] { 0, 1, 2, 5, 6 }));
            Assert.That(matches.Select(m => m.Groups[1].Length), Is.All.EqualTo(1));
            Assert.That(matches.Select(m => m.Groups[1].Value), Is.All.EqualTo("a"));
        }
예제 #12
0
        public void should_handle_end_before_start()
        {
            var re      = new PcreRegex(@"(?=a+b\K)");
            var matches = re.Matches("aaabab").ToList();

            Assert.That(matches, Has.Count.EqualTo(2));

            Assert.That(matches[0], Is.Not.Null);
            Assert.That(matches[0].Index, Is.EqualTo(4));
            Assert.That(matches[0].EndIndex, Is.EqualTo(0));
            Assert.That(matches[0].Length, Is.EqualTo(0));
            Assert.That(matches[0].Value, Is.EqualTo(string.Empty));

            Assert.That(matches[1], Is.Not.Null);
            Assert.That(matches[1].Index, Is.EqualTo(6));
            Assert.That(matches[1].EndIndex, Is.EqualTo(4));
            Assert.That(matches[1].Length, Is.EqualTo(0));
            Assert.That(matches[1].Value, Is.EqualTo(string.Empty));
        }
예제 #13
0
        public void should_handle_end_before_start_ref()
        {
            var re      = new PcreRegex(@"(?=a+b\K)");
            var matches = re.Matches("aaabab".AsSpan())
                          .ToList(m => (Value: m.Value.ToString(), m.Index, m.EndIndex, m.Length, Groups: m.Groups.ToList(g => (Value: g.Value.ToString(), g.Index, g.Length))));

            Assert.That(matches, Has.Count.EqualTo(2));

            Assert.That(matches[0], Is.Not.Null);
            Assert.That(matches[0].Index, Is.EqualTo(4));
            Assert.That(matches[0].EndIndex, Is.EqualTo(0));
            Assert.That(matches[0].Length, Is.EqualTo(0));
            Assert.That(matches[0].Value, Is.EqualTo(string.Empty));

            Assert.That(matches[1], Is.Not.Null);
            Assert.That(matches[1].Index, Is.EqualTo(6));
            Assert.That(matches[1].EndIndex, Is.EqualTo(4));
            Assert.That(matches[1].Length, Is.EqualTo(0));
            Assert.That(matches[1].Value, Is.EqualTo(string.Empty));
        }
예제 #14
0
        /// <summary>
        /// Сохранение музыкальных треков
        /// </summary>
        /// <param name="trakList">Список треков одного релиза</param>
        /// <param name="musicId">ID релиза</param>
        private void SaveMusicTrack(string trakList, int musicId)
        {
            var trackListRelease = PcreRegex.Matches(trakList, Helper.ReleaseTrackListPattern)
                                   .Select(m => m.Value).ToList();

            //обрабатываем треклист
            foreach (var track in trackListRelease)
            {
                var trackEntity = _unitOfWork.MusicTrackRepository.Queryable().
                                  FirstOrDefault(t => t.Title.Equals(track) && t.DbMusicId == musicId);
                if (trackEntity == null)
                {
                    _unitOfWork.MusicTrackRepository.Insert(new DbMusicTrack
                    {
                        Title     = track,
                        DbMusicId = musicId
                    });
                }
            }

            _unitOfWork.SaveChanges();
        }
예제 #15
0
        public void should_return_all_matches()
        {
            var re      = new PcreRegex(@"a(b)a");
            var matches = re.Matches("foo aba bar aba baz").ToList();

            Assert.That(matches, Has.Count.EqualTo(2));

            Assert.That(matches[0].Value, Is.EqualTo("aba"));
            Assert.That(matches[0].Index, Is.EqualTo(4));
            Assert.That(matches[0].Length, Is.EqualTo(3));

            Assert.That(matches[0][1].Value, Is.EqualTo("b"));
            Assert.That(matches[0][1].Index, Is.EqualTo(5));
            Assert.That(matches[0][1].Length, Is.EqualTo(1));

            Assert.That(matches[1].Value, Is.EqualTo("aba"));
            Assert.That(matches[1].Index, Is.EqualTo(12));
            Assert.That(matches[1].Length, Is.EqualTo(3));

            Assert.That(matches[1][1].Value, Is.EqualTo("b"));
            Assert.That(matches[1][1].Index, Is.EqualTo(13));
            Assert.That(matches[1][1].Length, Is.EqualTo(1));
        }
예제 #16
0
        public void should_return_all_matches_ref()
        {
            var re      = new PcreRegex(@"a(b)a");
            var matches = re.Matches("foo aba bar aba baz".AsSpan())
                          .ToList(m => (Value: m.Value.ToString(), m.Index, m.Length, Groups: m.Groups.ToList(g => (Value: g.Value.ToString(), g.Index, g.Length))));

            Assert.That(matches, Has.Count.EqualTo(2));

            Assert.That(matches[0].Value, Is.EqualTo("aba"));
            Assert.That(matches[0].Index, Is.EqualTo(4));
            Assert.That(matches[0].Length, Is.EqualTo(3));

            Assert.That(matches[0].Groups[1].Value, Is.EqualTo("b"));
            Assert.That(matches[0].Groups[1].Index, Is.EqualTo(5));
            Assert.That(matches[0].Groups[1].Length, Is.EqualTo(1));

            Assert.That(matches[1].Value, Is.EqualTo("aba"));
            Assert.That(matches[1].Index, Is.EqualTo(12));
            Assert.That(matches[1].Length, Is.EqualTo(3));

            Assert.That(matches[1].Groups[1].Value, Is.EqualTo("b"));
            Assert.That(matches[1].Groups[1].Index, Is.EqualTo(13));
            Assert.That(matches[1].Groups[1].Length, Is.EqualTo(1));
        }
예제 #17
0
        public void should_report_callout_exception()
        {
            var re = new PcreRegex(@"a(?C1)");

            var resultCount = 0;

            var seq = re.Matches("aaa", 0, callout =>
            {
                if (callout.StartOffset >= 2)
                {
                    throw new InvalidOperationException("Simulated exception");
                }

                return(PcreCalloutResult.Pass);
            }).Select(i =>
            {
                ++resultCount;
                return(i);
            });

            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            Assert.Throws <PcreCalloutException>(() => seq.ToList());
            Assert.That(resultCount, Is.EqualTo(2));
        }
예제 #18
0
        private static void RunTest(TestCase testCase, TestOutput expectedResult, PcreOptions options)
        {
            options = (options | testCase.Pattern.PatternOptions) & ~testCase.Pattern.ResetOptionBits;

            Console.WriteLine("Options: {0}", options);

            PcreRegex regex;

            try
            {
                regex = new PcreRegex(testCase.Pattern.Pattern, options);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains(@"\C is not allowed in a lookbehind assertion"))
                {
                    Assert.Inconclusive(ex.Message);
                }

                throw;
            }

            for (var line = 0; line < testCase.SubjectLines.Count; ++line)
            {
                Console.WriteLine("  Subject #{0}: {1}", line, testCase.SubjectLines[line]);

                var subject  = testCase.SubjectLines[line];
                var expected = expectedResult.ExpectedResults[line];

                Assert.That(expected.SubjectLine, Is.EqualTo(subject));

                subject = testCase.Pattern.HexEncoding
                    ? subject.UnescapeBinarySubject()
                    : subject.UnescapeSubject();

                var matches = regex
                              .Matches(subject)
                              .Take(testCase.Pattern.AllMatches ? int.MaxValue : 1)
                              .ToList();

                Assert.That(matches.Count, Is.EqualTo(expected.Matches.Count));

                for (var matchIndex = 0; matchIndex < matches.Count; ++matchIndex)
                {
                    var actualMatch   = matches[matchIndex];
                    var expectedMatch = expected.Matches[matchIndex];

                    CompareGroups(actualMatch, expectedMatch);

                    if (testCase.Pattern.ExtractMarks)
                    {
                        CompareMark(actualMatch, expectedMatch);
                    }

                    if (testCase.Pattern.GetRemainingString)
                    {
                        CompareRemainingString(actualMatch, expectedMatch);
                    }
                }
            }

            Console.WriteLine("OK");
            Console.WriteLine();
        }
예제 #19
0
        private static void RunTest(TestInput testInput, TestOutput expectedResult, PcreOptions options, bool span)
        {
            var pattern = testInput.Pattern;

            if (pattern.NotSupported)
            {
                Assert.Inconclusive("Feature not supported");
            }

            options = (options | pattern.PatternOptions) & ~pattern.ResetOptionBits;

            PcreRegex regex;

            try
            {
                regex = new PcreRegex(pattern.Pattern, options);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains(@"\C is not allowed in a lookbehind assertion"))
                {
                    Assert.Inconclusive(ex.Message);
                }

                throw;
            }

            var jitStack = pattern.JitStack != 0 && (options & PcreOptions.Compiled) != 0
                ? new PcreJitStack(1, pattern.JitStack)
                : null;

            using (jitStack)
            {
                for (var line = 0; line < testInput.SubjectLines.Count; ++line)
                {
                    var subject  = testInput.SubjectLines[line];
                    var expected = expectedResult.ExpectedResults[line];

                    Assert.That(expected.SubjectLine, Is.EqualTo(subject));

                    if (!pattern.SubjectLiteral)
                    {
                        subject = pattern.HexEncoding
                            ? subject.UnescapeBinarySubject()
                            : subject.UnescapeSubject();
                    }

                    var matchSettings = new PcreMatchSettings
                    {
                        JitStack = jitStack
                    };

                    if (span)
                    {
                        var matchCount = 0;

                        foreach (var actualMatch in regex.Matches(subject.AsSpan(), matchSettings))
                        {
                            Assert.That(matchCount, Is.LessThan(expected.Matches.Count));

                            var expectedMatch = expected.Matches[matchCount];
                            ++matchCount;

                            CompareGroups(pattern, actualMatch, expectedMatch);

                            if (pattern.ExtractMarks)
                            {
                                CompareMark(actualMatch, expectedMatch);
                            }

                            if (pattern.GetRemainingString)
                            {
                                CompareRemainingString(actualMatch, expectedMatch);
                            }

                            if (!pattern.AllMatches)
                            {
                                break;
                            }
                        }

                        Assert.That(matchCount, Is.EqualTo(expected.Matches.Count));
                    }
                    else
                    {
                        var matches = regex
                                      .Matches(subject, matchSettings)
                                      .Take(pattern.AllMatches ? int.MaxValue : 1)
                                      .ToList();

                        Assert.That(matches.Count, Is.EqualTo(expected.Matches.Count));

                        for (var matchIndex = 0; matchIndex < matches.Count; ++matchIndex)
                        {
                            var actualMatch   = matches[matchIndex];
                            var expectedMatch = expected.Matches[matchIndex];

                            CompareGroups(pattern, actualMatch, expectedMatch);

                            if (pattern.ExtractMarks)
                            {
                                CompareMark(actualMatch, expectedMatch);
                            }

                            if (pattern.GetRemainingString)
                            {
                                CompareRemainingString(actualMatch, expectedMatch);
                            }
                        }
                    }
                }
            }
        }
예제 #20
0
        public IEnumerable <string> Matches(string input, string pattern)
        {
            var matches = PcreRegex.Matches(input, pattern, PcreOptions.IgnoreCase);

            return(matches.SelectMany(m => m.Groups.Select(g => g.Value)));
        }
 static void Main(string[] args)
 {
     var marks = PcreRegex.Matches("bar", "(?|foo(*:1)|bar(*:2)|baz(*:3))")
                 .Select(m => m.Mark)
                 .ToList();
 }