473,598 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regular Expressions in C#

Hello all,

I am attempting to create a small scripting application to be used
during testing. I extract the commands from the script file I was going
to tokenize the each line as one of the requirements is there one
command per line. I have always wanted to learn Regular Expressions, so
I was hoping I might do this using Regular Expressions. For a fair
number of the command will have the syntax like

Write( 0x123, 0x12, 25, 100 ) <- Write three bytes to address 0x123
Write(varName1, 0x12) <- Write one bytes to address
expressed by the value of
varName1
Read( 0x55, 5 ) <- Write one bytes to address 0x55
Read(0x3456, 0x12) <- Read eighteen bytes to address
0x3456
varName2 = Read( varName1 ) <- Read one byte from address
expressed by the value of varName1
and store that read value to
varName2
I know if I use the regular expression (^[a-zA-Z]*) will find the
initial keywords or variable names which I can perform an initial check
to make sure they are valid or the variable has been declared already,
but the hard part is creating a regular expression to match the various
forms of the syntax. How would I create a regular express for the first
and last script commands? I think with those I can attempt to determine
the others. The spaces between the arguments are optional and may be
omitted if the user so desires.

For the first script command I was attempting to craft one that looks
like..

(^[a-zA-Z]*)('\(')(['0x',0-9][a-zA-Z]*)(',')(['0x',0-9][a-zA-Z]*)

but this obviously doesn't work. Any help is greatly appreciated.

Mark

Apr 13 '06 #1
3 3322
Hi Mark,

For parsing script commands you might consider using a lexical analyser
like CsLex or C# Lex, maybe with a grammer parser such as GPPG.

To match you first command, try something like:
\w+\((\s*0x\d+\ s*,\s*{2}\d+\s* ,\s*\d+\s*\)

There's a great regexp reference here:
http://www.regular-expressions.info/reference.html

HTH,
Chris

Apr 14 '06 #2
I couldn't help but bite on this one. It is a very challenging problem. Here
is your solution:

(?i)(?:(?<funct ion>Write|Read) \s*\()\s*|(?<=( ?:(?:Write|Read )\s*\(\s*)|(?:( ?:[\d\w]+\s*,\s*)))(?<p arameter>[\d\w]+)(?=,\s*|\s*\) )

Let me break it down a bit. First, I used (?i) to indicate that it is
non-case-sensitive.
Next, I had the problem of identifying *both* function names and parameters
in the same Regular Expression.

The function name Regular Expression is:

(?:(?<function> Write|Read)\s*\ (\s*)

"function" is the name of the capturing group, which captures only the
function name. The rest of the match is to identify it as a function.

It will match only if the function name is "Read" or "Write" and is followed
by an opening parenthesis. I assumed that any token may have any number of
white-space characters before and after it. This was not too tricky.

The second one is a bit trickier:

(?<=(?:(?:Write |Read)\s*\(\s*) |(?:(?:[\d\w]+\s*,\s*)))(?<p arameter>[\d\w]+)(?=,\s*|\s*\) )

The trick here is to identify a parameter from inside a set of function
parameters.

The rules break down as:

1. A parameter is always preceded by a function name followed by an open
parenthesis, as in:

Write (

2. It may be preceded by another parameter followed by a comma.

Write(param1,

- or -

Write(.......pa ram3,

3. It is always followed by either a comma or an end-parenthesis.

param1,
- or -
param2 )

So, starting with the third rule, we get:

(?<parameter>[\d\w]+)(?=,\s*|\s*\) )

"parameter" is the name of the capturing group, which according to these
rules is an alphanumeric token. The rest of it is how the parameter is
matched. It is a positive look-ahead, which means that it *must* be followed
by either a comma or an end parenthesis.

However, the problem here is that *any* word in the string that is not a
function and is followed by a comma or an end parenthesis will match this,
as in:

Read( 0x55, 5 ) <- Write one byte, to (address 0x55)

In this line, "byte," and "(address 0x55)" will match.

So, how do we eliminate non-parameters? Well, obviously, a parameter is
defined as being inside the parentheses of a function call. So, first, use a
positive look-behind to see if it is preceded by a function call. We need to
identify the function, using the same syntax as before:

(?:(?:Write|Rea d)\s*\(\s*)

However, it may have a parameter before it, instead of the function call. So
we use an OR "|" operator to indicate that it may be preceded by:

(?:(?:[\d\w]+\s*,\s*))

Note that we have changed the rule slightly. Any parameter which precedes
another parameter will *not* be followed by an end-parenthesis. It will
*always* be followed by a comma.

So, we use the Positive Lookbehind syntax (?>=) coupled with an OR operator
("|"), and get:

(?<=(?:(?:Write |Read)\s*\(\s*) |(?:(?:[\d\w]+\s*,\s*)))(?<p arameter>[\d\w]+)(?=,\s*|\s*\) )

Translated: Match any alphanumeric set of tokens which is followed by either
a comma or an end parenthesis, and is preceded either by a function call or
by another parameter.

Now to put them together, we use the OR operator:

(?i)(?:(?<funct ion>Write|Read) \s*\()\s*|(?<=( ?:(?:Write|Read )\s*\(\s*)|(?:( ?:[\d\w]+\s*,\s*)))(?<p arameter>[\d\w]+)(?=,\s*|\s*\) )

The function name will be captured into the "function" group, and all of the
parameters will be captured into the "parameter" group. This could be stated
as:

Match any token that is either "Read" or "Write" followed by an open
parenthesis, and call it "function," OR Match any alphanumeric set of tokens
which is followed by either a comma or an end parenthesis, and is preceded
either by a function call or by another parameter, and call it "parameter. "

You sure picked a doozy to start out with!

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

<Lo*****@hotmai l.com> wrote in message
news:11******** *************@u 72g2000cwu.goog legroups.com...
Hello all,

I am attempting to create a small scripting application to be used
during testing. I extract the commands from the script file I was going
to tokenize the each line as one of the requirements is there one
command per line. I have always wanted to learn Regular Expressions, so
I was hoping I might do this using Regular Expressions. For a fair
number of the command will have the syntax like

Write( 0x123, 0x12, 25, 100 ) <- Write three bytes to address 0x123
Write(varName1, 0x12) <- Write one bytes to address
expressed by the value of
varName1
Read( 0x55, 5 ) <- Write one bytes to address 0x55
Read(0x3456, 0x12) <- Read eighteen bytes to address
0x3456
varName2 = Read( varName1 ) <- Read one byte from address
expressed by the value of varName1
and store that read value to
varName2
I know if I use the regular expression (^[a-zA-Z]*) will find the
initial keywords or variable names which I can perform an initial check
to make sure they are valid or the variable has been declared already,
but the hard part is creating a regular expression to match the various
forms of the syntax. How would I create a regular express for the first
and last script commands? I think with those I can attempt to determine
the others. The spaces between the arguments are optional and may be
omitted if the user so desires.

For the first script command I was attempting to craft one that looks
like..

(^[a-zA-Z]*)('\(')(['0x',0-9][a-zA-Z]*)(',')(['0x',0-9][a-zA-Z]*)

but this obviously doesn't work. Any help is greatly appreciated.

Mark

Apr 14 '06 #3
Kevin,

Thanks for providing a response and I am sorry for such a long delay
in my follow-up. I found help in the RegEx group which helped out a
great deal. I wanted to share the RegEx that I have thus far. They are
not fully testest, but they are functional for the most part. I used
unnamed groups for just about everything since that is just how I
decided to parse everything out. Perhaps I might change it in the
future if I find this approach problematic.

So here we go...
Syntax format: Write( address, data [, 44] )

\s*Write\s*\((? :\s*(\d+|0x[\dA-Fa-f]+|[a-zA-Z][\da-zA-Z]*){1,1}(?:\s*,\ s*(\d+|0x[\dA-Fa-f]+|[a-zA-Z][\da-zA-Z]*))*\s*\))\s*$

Syntax format: [variable3 =] Read( 0x44 [, 44] )

Group 1 : Optional: variable name with equal sign
(e.g. "variable2 =")
Group 2 : Required: Read keyword
Group 3 : Required: Address
Group 4 : Optional: Number of bytes to read starting at 'Address'

^\s*(?:([a-zA-Z][a-zA-z\d]\w*)\s*=\s*){0, 1}(?:\s*(Read){ 1,1}\s*)\((?:\s *(\d+|0x[\dA-Fa-f]+|[a-zA-Z][\da-zA-Z]*)(?:\s*,\s*(\d +|0x[\dA-Fa-f]+|[a-zA-Z][\da-zA-Z]*))*\s*\))\s*$
This one is rather long, but there are multiple cases that I need to
account for. I could have created a RegEx for each individual case,
but I rather have one all encompassing one then check each of the
parameters instead of processing each RegEx which I think would be
slower. For these, you can change byte to short, int and float which
is used in my application.
Syntax format: byte var1

Group 1 : Required: var1
Group 2 : Optional: Not Present
Group 3 : Optional: Not Present
Group 4 : Optional: Not Present
Group 5 : Optional: Not Present
Group 6 : Optional: Not Present
Group 7 : Optional: Not Present

----------------------------------------------

Syntax format: byte var2 = variableNew

Group 1 : Required: var2
Group 2 : Optional: Not Present
Group 3 : Optional: Not Present
Group 4 : Optional: Not Present
Group 5 : Optional: variableNew
Group 6 : Optional: Not Present
Group 7 : Optional: Not Present

----------------------------------------------

Syntax format: byte var3[3] = { 0x11, 0xAA, 0x33 }

Group 1 : Required: var3
Group 2 : Optional: 3
Group 3 : Optional: 0x11
Group 4 : Optional:
Capture 1: 0xAA
Capture 2: 0x33
Group 5 : Optional: Not Present
Group 6 : Optional: Not Present
Group 7 : Optional: Not Present

----------------------------------------------

Syntax format: byte var4[] = { 0x33, 0x444 }

Group 1 : Required: var4
Group 2 : Optional: Not Present
Group 3 : Optional: 0x33
Group 4 : Optional: 0x444
Group 5 : Optional: Not Present
Group 6 : Optional: Not Present
Group 7 : Optional: Not Present

----------------------------------------------

Syntax format: byte var5[5] = 5555

Group 1 : Required: var5
Group 2 : Optional: Not Present
Group 3 : Optional: Not Present
Group 4 : Optional: Not Present
Group 5 : Optional: Not Present
Group 6 : Optional: 5
^\s*byte
(?:\s*([a-zA-Z][\da-zA-Z]*))(?:\[(?:\s*(\d+)\s*) ?\]\s*=\s*(?:\s*\{ \s*(\d+|0x[\dA-Fa-f]*)(?:\s*,\s*(\d +|0x[\dA-Fa-f]*))*\s*\})|\s*= \s*(?:(\d+|0x[\dA-Fa-f]+|[a-zA-Z][\da-zA-Z]*))|(?:\[(?:\s*(\d+)\s*) ?\]\s*=\s*(\d+|0x[\dA-Fa-f]+|[a-zA-Z][\da-zA-Z]*)))?\s*$

Syntax format: SetCommParam(CO Mn, BaudRate, DataBits, StopBits,
Parity)

Note: The Comm Port and Parity strings are case sensitive

Group 1 : Required: Port Number { COMn }
Group 2 : Required: Baud Rate
Group 3 : Required: DataBits
Group 4 : Required: StopBits
Group 5 : Required: Parity { None, Odd, Even, Mark, Space }

^\s*SetCommPara m\s*\(\s*(?:(CO M\d+))\s*,\s*(? :(\d+))\s*,\s*( ?:([5-8])){1,1}\s*,\s*( ?:(1|1.5|2))\s* ,\s*(?:(None|Od d|Even|Mark|Spa ce))\s*\)\s*$
I hope this might help someone else in the future. Thanks too all of
the great people on the newsgroups and forums.

Mark

May 23 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2421
by: Michael McGarry | last post by:
Hi, I am horrible with Regular Expressions, can anyone recommend a book on it? Also I am trying to parse the following string to extract the number after load average. ".... load average: 0.04, 0.02, 0.01" how can I extract this number with RE or otherwise?
1
4159
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make regular expressions easier to create and use (and in my experience as a regular expression user, it makes them MUCH easier to create and use.) I'm still working on formal documentation, and in any case, such documentation isn't necessarily the...
2
5031
by: Sehboo | last post by:
Hi, I have several regular expressions that I need to run against documents. Is it possible to combine several expressions in one expression in Regex object. So that it is faster, or will I have to use all the expressions seperately? Here are my regular expressions that check for valid email address and link Dim Expression As String =
4
5153
by: Együd Csaba | last post by:
Hi All, I'd like to "compress" the following two filter expressions into one - assuming that it makes sense regarding query execution performance. .... where (adate LIKE "2004.01.10 __:30" or adate LIKE "2004.01.10 __:15") .... into something like this: .... where adate LIKE "2004.01.10 __:(30/15)" ...
7
3807
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
3
3012
by: a | last post by:
I'm a newbie needing to use some Regular Expressions in PHP. Can I safely use the results of my tests using 'The Regex Coach' (http://www.weitz.de/regex-coach/index.html) Are the Regular Expressions used in Perl identical to the Regular Expressions in PHP?
25
5141
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
4373
by: Allan Ebdrup | last post by:
I have a dynamic list of regular expressions, the expressions don't change very often but they can change. And I have a single string that I want to match the regular expressions against and find the first regular expression that matches the string. I've gor the regular expressions ordered so that the highest priority is first (if two or more regular expressions match the string I want the first one returned) The code that does this has...
13
7471
by: Wiseman | last post by:
I'm kind of disappointed with the re regular expressions module. In particular, the lack of support for recursion ( (?R) or (?n) ) is a major drawback to me. There are so many great things that can be accomplished with regular expressions this way, such as validating a mathematical expression or parsing a language with nested parens, quoting or expressions. Another feature I'm missing is once-only subpatterns and possessive quantifiers...
12
2457
by: FAQEditor | last post by:
Anybody have any URL's to tutorials and/or references for Regular Expressions? The four I have so far are: http://docs.sun.com/source/816-6408-10/regexp.htm http://en.wikipedia.org/wiki/Regular_expression http://www.regular-expressions.info/javascript.html http://www.webreference.com/js/column5/
0
7894
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8284
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
8392
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
8046
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
8262
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...
1
5847
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
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
3894
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...
0
3938
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.