Monday, October 5, 2015

Regular expressions to resolve different requirements

Issue 1>
I was having requirement that I want to find all words in two consecutive % characters. Below interesting regular expression I used for that.

%[\w\s\S]*?%

\w for alphabet and underscore
\s for space
\S for special chars
? returns shortest possible match

Edit the% my file % %% %kjghjhgkjg % % (**&*&*&*&*&*&*& % %9089898098% Expression

Highlighted are the matches.

http://regexr.com/3btui see for more details.

The c#.net code used as below to find all these matches.

            MatchCollection allMatchResults = null;
            var regexObj = new Regex(@"%[\w\s\S]*?%");  
            allMatchResults = regexObj.Matches(this.textBox1.Text);

            string output = "";
            foreach (var s in allMatchResults)
            {
                output += s + "\n";
            }

            label1.Text = output;