Пример #1
0
        public void RegexCreateExposesCaptureGroupInfo()
        {
            //Given
            var regex = new Regex("(.+) (?P<foo>.*)");

            //When
            var numCaptures      = regex.CaptureGroupCount;
            var fooCaptureId     = regex.FindNamedCapture("foo");
            var invalidCaptureId = regex.FindNamedCapture("bar");

            //Then
            Assert.Equal(2, numCaptures);
            Assert.Equal(2, fooCaptureId);
            Assert.Equal(-1, invalidCaptureId);
        }
Пример #2
0
        public void CapturesWithExtractedText()
        {
            using (var re = new Regex(@"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"))
            {
                var haystack = "The first woman in space launched on 1963-06-16 in Vostok 6";

                var captures = re.Captures(haystack);

                Assert.True(captures.Matched);

                // The first capture group is the whole match.
                Assert.True(captures[0].Matched);

                // Each capture group has position information
                Assert.True(captures[1].Matched);
                Assert.Equal(37, captures[1].Start);
                Assert.Equal(41, captures[1].End);

                /// As well as the UTF-8 indices the extracted text is available
                Assert.True(captures[2].Matched);
                Assert.Equal("06", captures[2].ExtractedText);

                // capture group indices can be looked up by name with th `Regex`
                Assert.True(captures[re.FindNamedCapture("day")].Matched);
            }
        }