473,756 Members | 9,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to build long Regular Expression

1 New Member
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 6193

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

Similar topics

9
3154
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 strkey = "something"; var str = "Somethin like this"; if( str.search( / + strkey + / ) > -1 )
5
2531
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, and then reconstruct another URL based on it. For example, I need to scan a web page looking for something like <a href="some_dir/list_20050815100225.csv">. I don't know in advance what the date/time in the file name will be. I need to take the...
4
5171
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 testMyColumn{1, 100}Test Basically I want the regular expression to add the word test infront of the
4
3229
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 over each document, find out if it contains a header and/or a footer and extract only the main content part. The headers and the footers have no specific format and I have to detect and remove them using a list of strings that may appear as...
11
5391
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, I want to use the text included within the brackets to do a lookup so that I can replace the expression with the new text. For example:
7
3829
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 want to avoid that. My question here is if there is a way to pass either a memory stream or array of "find", "replace" expressions or any other way to avoid multiple copies of a string. Any help will be highly appreciated
9
3358
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 an app call The Regulator, which makes it pretty easy to build and test regular expressions. As a warning, I'm real weak with regular expressions. Let's say my regular expression is:
25
5166
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 (CONDUCTION DEFECT) 37.33/2 HEART (CONDUCTION DEFECT) WITH CATHETER 37.34/2 " the expression is "HEART (CONDUCTION DEFECT)". How do I gain access to the expression (not the matches) at runtime? Thanks, Mike
1
3408
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 "": --------------------------------- myStringVar = myStringVar.replace("^" + iName + "=,($|&)", ""); --------------------------------- The following DOES replace it though: --------------------------------- var match = myStringVar.match("^" + iName + "=,($|&)");
0
9482
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10062
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9901
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9878
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9728
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8733
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6551
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5167
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3392
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.