473,288 Members | 1,771 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,288 developers and data experts.

How to build long Regular Expression

Usually when you make regular expression to extract text you are starting from simple expression. When you got to know target text, you are extending your expression. Subsequently very hard to ready long set of special symbols and impossible to improve such expression.

We have to create ’smart’ regular expression. Instead of write one line expression we prepare multi line text from which we shall generate our long expression. Here is a simple example.

Expand|Select|Wrap|Line Numbers
  1. space                    [\s/-]+
  2. word                     \w+
  3. words                    (?:{word}{space})*?{word}
  4. birthday                 (?<birthday>\d+\.d+\.d+)
  5. title                    {word}\.
  6. name                     {words}
  7. person                   {title}{space}{name}{space}{birthday}
  8.  
This text consist of two columns separated by spaces. First column is pattern name and second column is easy to read regular expression. The resulting regular expression for pattern ‘person’ will be:
Expand|Select|Wrap|Line Numbers
  1. \w+\.[\s/-]+(?:\w+[\s/-]+)*?\w+[\s/-]+(?<birthday>\d+.\d+.\d+)
  2.  
You can do it using following class
Expand|Select|Wrap|Line Numbers
  1. public class Lexer
  2.     {
  3.         private NameValueCollection col;
  4.         public Lexer()
  5.         {
  6.             col = new NameValueCollection();
  7.         }
  8.  
  9.         public static Lexer Create(string resource)
  10.         {
  11.             StringReader sr = new StringReader(resource);
  12.             Lexer lex =new Lexer();
  13.             while (sr.Peek()>=0)
  14.             {
  15.                 string line = sr.ReadLine();
  16.                 Match m = Regex.Match(line,@"([\w_]+)\s+(.*)");
  17.                 if (m.Success) 
  18.                 {
  19.                     lex.col.Add(m.Groups[1].Value.Trim(), m.Groups[2].Value.Trim());
  20.                 }
  21.             }
  22.             sr.Close();
  23.  
  24.             return lex;
  25.         }
  26.  
  27.  
  28.         public string GetExpression(string name)
  29.         {
  30.             if (name == null || name.Length == 0) return string.Empty;
  31.             string res = col[name];
  32.             if (res == null) throw new ArgumentException("Template not found", name);
  33.  
  34.             bool needGroup = res.IndexOf('|') > 0;
  35.             Regex reg = new Regex(@"(?<!\\p){([a-zA-Z][\w_]+)}");
  36.             Match m = reg.Match(res);
  37.             while (m.Success)
  38.             {
  39.                 string token = m.Groups[1].Value;
  40.                 string exp = GetExpression(token); 
  41.                 if (exp != null && exp.Length>0)
  42.                     res = res.Replace(@"{"+token+"}",exp);
  43.                 m = m.NextMatch();
  44.             }
  45.             string result = res;
  46.             if (needGroup)
  47.             {
  48.                 result = "(?:" + res + ")";
  49.             }
  50.             result = "(?#" + name + ")" + result;
  51.  
  52.             return result;
  53.         }
  54.  
  55.     }
  56.  

Then we can create class instance and get regular expression
Expand|Select|Wrap|Line Numbers
  1. Lexer lex = Lexer.Create(txtLexerText.Text);
  2. string expr = lex.GetExpression("person");
  3. Regex reg = new Regex(expr);
  4.  
Oct 29 '07 #1
0 6162

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Harry | last post by:
Hi there, does anyone know how I can build a regular expression e.g. for the string.search() function on runtime, depending on the content of variables? Should be something like this: var...
5
by: Bradley Plett | last post by:
I'm hopeless at regular expressions (I just don't use them often enough to gain/maintain knowledge), but I need one now and am looking for help. I need to parse through a document to find a URL,...
4
by: Buddy | last post by:
Can someone please show me how to create a regular expression to do the following My text is set to MyColumn{1, 100} Test I want a regular expression that sets the text to the following...
4
by: Neri | last post by:
Some document processing program I write has to deal with documents that have headers and footers that are unnecessary for the main processing part. Therefore, I'm using a regular expression to go...
11
by: Dimitris Georgakopuolos | last post by:
Hello, I have a text file that I load up to a string. The text includes certain expression like {firstName} or {userName} that I want to match and then replace with a new expression. However,...
7
by: Billa | last post by:
Hi, I am replaceing a big string using different regular expressions (see some example at the end of the message). The problem is whenever I apply a "replace" it makes a new copy of string and I...
9
by: Pete Davis | last post by:
I'm using regular expressions to extract some data and some links from some web pages. I download the page and then I want to get a list of certain links. For building regular expressions, I use...
25
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART...
1
by: NvrBst | last post by:
I want to use the .replace() method with the regular expression /^ %VAR % =,($|&)/. The following DOESN'T replace the "^default.aspx=,($|&)" regular expression with "":...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.