473,756 Members | 2,900 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regular expression problem - Replacing a pattern

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:

Lets say the text file reads:
Hello {firstName}, Your account {accountName} has been updated.

I need to figure out how to write the expression so that the string
reads like:
Hello Dimitris, Your account Hotmail has been updated.

after the replacement. Keep in mind that I need to use the value
contained in the brackets so that I can do a lookup to figure what the
corresponding replacement is.

Any help would be appreciated.

Dimitris
Nov 16 '05
11 5390
aaaaaaaaaaaaaaa aaa
"Michael Voss" <mi**********@l vrREMOVE.deCAPS > wrote in message
news:40876fea$1 @news...
Oops - I should rather test the code I give away before posting...
I missed a very important "*" for the Regex to match not just one character between {}...
As Du pointed out, the { and } will have to be escaped. Then, you are
looking for everything between \{ and \}, so the regular expression to start
with would be "\{.*\}" which would detect wether there is any occurrence

of a
^
--------------------| need a "*" here to match more than one character

!!!!
pair of curly brackets in your string. Remember to put an @ in front of your
regular expression string, so C# knows the \ belong into your string and

are
not C#-escape-characters.
You will most likely want to find the shortest pair, as the expression

above
would find one occurence in our string, containing "firstName} , Your
account {accountName" between the pair of brackets. So we make the .*

"lazy"
^
----------------------------------------------------------------------|
need another "*" here to match more than one character !!!!
by adding a "?" behind. That makes "\{.*?\}" for our improved expression. ^
-----------------------------------------|
and another "*" goes here !!!!!!
This expression will match twice, with "firstname" and "accountnam e"
included between the two pairs of brackets.
Next, you want to remember the value that matches the regular
expression, so
we crate a named group: "\{(?'groupname '.*?)\}". This will find any sequence
^
-------------------------------------------|
ok, another "*" here ...
of characters (.*?) between a pair of curly brackets (\{ and \}) and

store it
^
------------------|
and "*" here again !!!!
in the group named "groupname" for each match. ?'groupname' names the group
(you can use ?<groupname> instead) and everything else between the ()

makes
the expression, that will be stored in the group "groupname" .
Finally, we want to iterate over the matches:

=============== =============== =============== =============== =============== =
string myString = "Hello {firstName}, Your account {accountName} has been updated.";

// Create a new regular expression
// Adding the Singleline-Option makes the . include \n-Characters.
// If there is no \n between {}, make it RegexOptions.No ne or
// do not add any option
Regex expression = new Regex(@"\{(?'gr oupname'.*?)\}" ,

^
-------------------------------------------------|
and again another "*" here !!!!!! That's it !
RegexOptions.Si ngleline);

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matc hes(myString);

// Iterate over the matches
foreach (Match foundOne in matchCol)
{
// Get the contents between the {} for the current match
// Will be "firstName" for the first match and "accountNam e"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDa taForKeyString( lookForMe);

// Finally, replace lookForMe by replacement in the source string
// We do this by a new regular expression which is built dynamically
// on the key we are processing...
myString = Regex.Replace(m yString, @"\{" + lookForMe + @\}",
replacement);
};

=============== =============== =============== =============== =============== =
Sorry, but I had no time to test it before I posted originally...

Nov 16 '05 #11
privet
"Boris" <bo*****@optonl ine.net> wrote in message
news:y5******** *************** @news4.srv.hcvl ny.cv.net...
lena test
"Michael Voss" <mi**********@l vrREMOVE.deCAPS > wrote in message
news:40876e39$1 @news...

"Michael Voss" <mi**********@l vrREMOVE.deCAPS > schrieb im Newsbeitrag
news:4083d5cb$1 @news...
Hi !

Dimitris Georgakopuolos wrote:
[...snip...]
> What I am trying to do is retrieve the values to do the
> replacement dynamically, therefore I do not know ahead of time in
> design time of the type of fields to look for; it could be
> {firstName} or {lastName} or 100 other fields that I don't want to
> hard code.
[...snip...]
> Would something like this work:
>
> return Regex.Replace(i nput,
> "{(?<name>} ",
> GetReplacement( "${name});
[...snip...]

Let's assume your string is "Hello {firstName}, Your account {accountName}
has been
updated."

As Du pointed out, the { and } will have to be escaped. Then, you are
looking for everything between \{ and \}, so the regular expression to

start
with would be "\{.\}" which would detect wether there is any occurrence of
a
pair of curly brackets in your string. Remember to put an @ in front
of
your
regular expression string, so C# knows the \ belong into your string
and are
not C#-escape-characters.
You will most likely want to find the shortest pair, as the expression

above
would find one occurence in our string, containing "firstName} , Your
account {accountName" between the pair of brackets. So we make the .

"lazy"
by adding a "?" behind. That makes "\{.?\}" for our improved

expression. This expression will match twice, with "firstname" and "accountnam e"
included between the two pairs of brackets.
Next, you want to remember the value that matches the regular

expression,
so
we crate a named group: "\{(?'groupname '.?)\}". This will find any

sequence
of characters (.?) between a pair of curly brackets (\{ and \}) and

store
it
in the group named "groupname" for each match. ?'groupname' names the

group
(you can use ?<groupname> instead) and everything else between the ()

makes
the expression, that will be stored in the group "groupname" .
Finally, we want to iterate over the matches:

=============== =============== =============== =============== =============== =
=====

string myString = "Hello {firstName}, Your account {accountName} has been updated.";

// Create a new regular expression
// Adding the Singleline-Option makes the . include \n-Characters.
// If there is no \n between {}, make it RegexOptions.No ne or
// do not add any option
Regex expression = new Regex(@"\{(?'gr oupname'.?)\}",
RegexOptions.Si ngleline);

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matc hes(myString);

// Iterate over the matches
foreach (Match foundOne in matchCol)
{
// Get the contents between the {} for the current match
// Will be "firstName" for the first match and "accountNam e"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDa taForKeyString( lookForMe);

// Finally, replace lookForMe by replacement in the source string
// We do this by a new regular expression which is built dynamically // on the key we are processing...
myString = Regex.Replace(m yString, @"\{" + lookForMe + @\}",
replacement);
};

=============== =============== =============== =============== =============== =
=====



Nov 16 '05 #12

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

Similar topics

14
3187
by: Tina Li | last post by:
Hello, I've been struggling with a regular expression for parsing XML files, which keeps giving the run time error "maximum recursion limit exceeded". Here is the pattern string: r'<code>(?P<c>.*?)</code>.*?<targetSeq name="(?P<tn>.*?)">.*?<target>(?P<t>.*?)</target>.*?<align>(?P<a>.*?)</align>.*?<template>(?P<temp>.*?)</template>.*?<an otherTag>(?P<at>.*?)</anotherTag>.*?<yetAnotherTag>(?P<yat>.*?)</yetAnotherTag>' The file format...
1
4181
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...
1
1656
by: William Morris | last post by:
Been pounding on this for an hour and eating up my day's productivity, so I thought I'd throw a question out there. (I'm also reading through the Google archives to try to find this answer...) Windows 2000 Small Business Server Using regular expressions for the first time, and having difficulty with the replace method. We're searching through a list of vehicle models, trying to replace what we get from the client data with correctly...
5
11347
by: Mahesha | last post by:
Hello, I need help in replacing one string pattern with another. Ex: I have a financial security expression like log(T 3.25 6/24/2004)/sqrt(T 4.5 6/19/2002) Here "T 3.25 6/24/2004" is a variable on which I need to perform log and then divide the result with 3.980. While parsing such expressions, I need to find all occurence of date values and replace "/" character with "~" character. I need to do this only for date portion of the
3
3220
by: James D. Marshall | last post by:
The issue at hand, I believe is my comprehension of using regular expression, specially to assist in replacing the expression with other text. using regular expression (\s*) my understanding is that this will one or more occurrences to replace all the white space between with a comma. This search ElseIf InStr(1, indivline, "$") Then insert a replace statement that uses the regular expression to find and replace all the white space...
8
388
by: P K | last post by:
I have an XML in which I have to comment out the <responseopt> tag the tags between this tag should not be commented I plan to use regular expressions The tags looks like this <responseopt value="1"><someothertag></someothertag></responseopt> <responseopt value="2"><someothertag></someothertag></responseopt>
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
17
11671
by: Randy Webb | last post by:
I know that the /g flag will match all occurrences. Is there a way, with a Regular Expression, to match all occurrences *except* the last one? pattern = /df/g; var myString = "asdfasdfasdfasdf"; var newString = myString.replace(pattern,'gh'); alert(newString) Gives me: asghasghasghasgh as it should. What I want: asghasghasghasdf Where the last one is not replaced.
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
0
9456
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
9275
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
10034
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
9872
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...
0
9713
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
8713
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
6534
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();...
1
3805
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3358
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.