By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,070 Members | 1,718 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,070 IT Pros & Developers. It's quick & easy.

Regular expression problem - Replacing a pattern

P: n/a
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 #1
Share this Question
Share on Google+
11 Replies


P: n/a
for simple replacement like this you can use "String.Relace()" function
without having to use Regex.

String template = "Hello {firstName}, Your account {accountName} has been
updated.";
String name = "Dimitris";
String account = "Hotmail";
String message = "";

message = template.Replace("{firstName}", name);
message = message.Replace("{accountName}", account);

Console.WriteLine("String Replate: " + message);

// Alternative: regex
// since { and } are control chars u have to escape using \
message = Regex.Replace(template, @"\{firstName\}", name);
message = Regex.Replace(message, @"\{accountName\}", account);

Console.WriteLine("Regex Replate: " + message);

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.
i'm not sure what mean here, can you explain it a little more

anyway hope that helps,

Du

"Dimitris Georgakopuolos" <di*******@hotmail.com> wrote in message
news:ea**************************@posting.google.c om... 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 #2

P: n/a
If you need to do a look-up somewhere, you can always use a MatchEvaluator.
Whatever is matched in this case will be sent to a function where you can return
the replacement result. If the match is firstName, then you can replace that
with
some user's first name. If the match is accountName, do your look-ups and
make the replacement for that.

It sounds like you want a generic tag replacement method and the MatchEvaluator
is exactly what you'd want in that case. Check out www.regexlib.com. A friend
of mine runs the site and they have loads of regular expressions stuff going on.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers

"Du Dang" <vi*******@hotmail.com> wrote in message
news:Ix********************@nnrp1.uunet.ca...
for simple replacement like this you can use "String.Relace()" function
without having to use Regex.

String template = "Hello {firstName}, Your account {accountName} has been
updated.";
String name = "Dimitris";
String account = "Hotmail";
String message = "";

message = template.Replace("{firstName}", name);
message = message.Replace("{accountName}", account);

Console.WriteLine("String Replate: " + message);

// Alternative: regex
// since { and } are control chars u have to escape using \
message = Regex.Replace(template, @"\{firstName\}", name);
message = Regex.Replace(message, @"\{accountName\}", account);

Console.WriteLine("Regex Replate: " + message);

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.


i'm not sure what mean here, can you explain it a little more

anyway hope that helps,

Du

"Dimitris Georgakopuolos" <di*******@hotmail.com> wrote in message
news:ea**************************@posting.google.c om...
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 #3

P: n/a
Du,

I appreciate your help. I apologize for not being clear the first
time around. 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.

I was looking at an example like this for dates and want to do
something similar for my scenario but I am not sure of the best way to
accomplish it:

return Regex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}");

Would something like this work:

return Regex.Replace(input,
"{(?<name>}",
GetReplacement("${name});

Thanks for all your help,

Dimitris

"Du Dang" <vi*******@hotmail.com> wrote in message news:<Ix********************@nnrp1.uunet.ca>...
for simple replacement like this you can use "String.Relace()" function
without having to use Regex.

String template = "Hello {firstName}, Your account {accountName} has been
updated.";
String name = "Dimitris";
String account = "Hotmail";
String message = "";

message = template.Replace("{firstName}", name);
message = message.Replace("{accountName}", account);

Console.WriteLine("String Replate: " + message);

// Alternative: regex
// since { and } are control chars u have to escape using \
message = Regex.Replace(template, @"\{firstName\}", name);
message = Regex.Replace(message, @"\{accountName\}", account);

Console.WriteLine("Regex Replate: " + message);

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.


i'm not sure what mean here, can you explain it a little more

anyway hope that helps,

Du

"Dimitris Georgakopuolos" <di*******@hotmail.com> wrote in message
news:ea**************************@posting.google.c om...
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 #4

P: n/a
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(input,
"{(?<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 "accountname"
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.None or
// do not add any option
Regex expression = new Regex(@"\{(?'groupname'.?)\}",
RegexOptions.Singleline);

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matches(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 "accountName"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDataForKeyString(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(myString, @"\{" + lookForMe + @\}",
replacement);
};

================================================== ==========================
=====
Nov 16 '05 #5

P: n/a
FYI, the code I posted previously has not been tested...
Nov 16 '05 #6

P: n/a
And add an additional ":
myString = Regex.Replace(myString, @"\{" + lookForMe + @"\}",

^
missing "-------------------------------------------------|
Nov 16 '05 #7

P: n/a

"Michael Voss" <mi**********@lvrREMOVE.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(input,
"{(?<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 "accountname"
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.None or
// do not add any option
Regex expression = new Regex(@"\{(?'groupname'.?)\}",
RegexOptions.Singleline);

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matches(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 "accountName"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDataForKeyString(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(myString, @"\{" + lookForMe + @\}",
replacement);
};

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

Nov 16 '05 #8

P: n/a
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 "accountname"
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.None or
// do not add any option
Regex expression = new Regex(@"\{(?'groupname'.*?)\}", ^
-------------------------------------------------|
and again another "*" here !!!!!! That's it !
RegexOptions.Singleline);

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matches(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 "accountName"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDataForKeyString(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(myString, @"\{" + lookForMe + @\}",
replacement);
};

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

Sorry, but I had no time to test it before I posted originally...
Nov 16 '05 #9

P: n/a
lena test
"Michael Voss" <mi**********@lvrREMOVE.deCAPS> wrote in message
news:40876e39$1@news...

"Michael Voss" <mi**********@lvrREMOVE.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(input,
"{(?<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 "accountname"
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.None or
// do not add any option
Regex expression = new Regex(@"\{(?'groupname'.?)\}",
RegexOptions.Singleline);

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matches(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 "accountName"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDataForKeyString(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(myString, @"\{" + lookForMe + @\}",
replacement);
};

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


Nov 16 '05 #10

P: n/a
aaaaaaaaaaaaaaaaaa
"Michael Voss" <mi**********@lvrREMOVE.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 "accountname"
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.None or
// do not add any option
Regex expression = new Regex(@"\{(?'groupname'.*?)\}",

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

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matches(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 "accountName"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDataForKeyString(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(myString, @"\{" + lookForMe + @\}",
replacement);
};

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

Nov 16 '05 #11

P: n/a
privet
"Boris" <bo*****@optonline.net> wrote in message
news:y5***********************@news4.srv.hcvlny.cv .net...
lena test
"Michael Voss" <mi**********@lvrREMOVE.deCAPS> wrote in message
news:40876e39$1@news...

"Michael Voss" <mi**********@lvrREMOVE.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(input,
> "{(?<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 "accountname"
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.None or
// do not add any option
Regex expression = new Regex(@"\{(?'groupname'.?)\}",
RegexOptions.Singleline);

// Find all matches for our regular expression in myString
MatchCollection matchCol = expression.Matches(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 "accountName"
// for the second match
string lookForMe = foundOne.Groups["groupname"].Value;

// Find the Value to replace lookForMe with
string replacement = this.findSomeDataForKeyString(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(myString, @"\{" + lookForMe + @\}",
replacement);
};

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



Nov 16 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.