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 11 5383
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.Replac e("{firstName}" , name);
message = message.Replace ("{accountName} ", account);
Console.WriteLi ne("String Replate: " + message);
// Alternative: regex
// since { and } are control chars u have to escape using \
message = Regex.Replace(t emplate, @"\{firstName\} ", name);
message = Regex.Replace(m essage, @"\{accountName \}", account);
Console.WriteLi ne("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*******@hotm ail.com> wrote in message
news:ea******** *************** ***@posting.goo gle.com... 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
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*******@hotm ail.com> wrote in message
news:Ix******** ************@nn rp1.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.Replac e("{firstName}" , name); message = message.Replace ("{accountName} ", account);
Console.WriteLi ne("String Replate: " + message);
// Alternative: regex // since { and } are control chars u have to escape using \ message = Regex.Replace(t emplate, @"\{firstName\} ", name); message = Regex.Replace(m essage, @"\{accountName \}", account);
Console.WriteLi ne("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*******@hotm ail.com> wrote in message news:ea******** *************** ***@posting.goo gle.com... 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
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(i nput,
"\\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(i nput,
"{(?<name>} ",
GetReplacement( "${name});
Thanks for all your help,
Dimitris
"Du Dang" <vi*******@hotm ail.com> wrote in message news:<Ix******* *************@n nrp1.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.Replac e("{firstName}" , name); message = message.Replace ("{accountName} ", account);
Console.WriteLi ne("String Replate: " + message);
// Alternative: regex // since { and } are control chars u have to escape using \ message = Regex.Replace(t emplate, @"\{firstName\} ", name); message = Regex.Replace(m essage, @"\{accountName \}", account);
Console.WriteLi ne("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*******@hotm ail.com> wrote in message news:ea******** *************** ***@posting.goo gle.com... 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
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);
};
=============== =============== =============== =============== =============== =
=====
FYI, the code I posted previously has not been tested...
And add an additional ": myString = Regex.Replace(m yString, @"\{" + lookForMe + @"\}",
^
missing "-------------------------------------------------|
"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); };
=============== =============== =============== =============== =============== = =====
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...
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); };
=============== =============== =============== =============== =============== = =====
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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...
|
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...
|
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
|
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...
| |
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>
|
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
|
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.
|
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
|
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...
|
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...
| |
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,...
|
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |