What s Left?

We re in pretty good shape for regular expressions now, though there are a number of things we might want to learn about. One complication is that you can apparently get all the matches that are possible when a pattern matches several times on one string. I have no immediate use for that, so probably won t go there. Another complication is that Regex has a Replace method that will produce a new string with a replacement done based on the pattern. We ll probably need that one, when we replace a p-tagged string with an H2-tagged string. I m bored with this game right now, so will leave the Replace tests until I get that story.

Wait! I Just Thought...

In the example above, I have the \k, but it s followed by a .* left over from the original pattern. I bet that s redundant in this case. I ll change the test to remove that and see if it still runs. Sure enough, it still works. The backreference eats all the characters , given the pattern we have. I bet you could do some tricky things with that feature, such as embedding backreferences in other patterns, but I m not going to mess with that for now. For the record, here s the final version of the test. The only difference is the removal of the .* after the second occurrence of <prefix>.

 [Test] public void Backreference() { 
Regex r = new Regex("<(?<prefix>.*)>(?<body>.*)</(\k<prefix>)>");
Match m = r.Match("<p>this is a para</p>");
m = r.Match("<p>this is a para</H2>");

That s enough playing with Regex for now. What have we learned? What we have here is a small set of tests that were used to learn how to use Regex, and that now document that learning so that I can refer to it later and so that other programmers, like Chet when he sees this, can learn from it as well. It took a little more discipline to start testing Regex instead of just doing little experiments with printing, but to me the payoff is clear: this material can be used to pass on the learning to others and to my future forgetful self. I think it s worth it, and I commend the idea to your attention.

Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net