473,239 Members | 1,493 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,239 software developers and data experts.

Find specific pattern in a string

Hai ,

in a textbox am having text as
"(20/100)+pay1*pay2" .it's a formula. and stored in a particular
variable.
string strformula="(20/100)+pay1*pay2" ;

i've to substitute the value of the variable 'pay1' & 'pay2' and
finding the value of that strformula.
can any onr tell me how to find 'pay1' and 'pay2' in the variable
strformula. it's urgent and reply immediately.
Thanks in advance.

Feb 11 '06 #1
10 8933
Are they always going to be called "pay1" and "pay2"? Is the formula
always going to be the same? If not, what can change?

You need to give more examples of different formulas (if you can have
different formulas) in order that we know what the parameters of the
problem are. One example isn't enough.

Feb 11 '06 #2
the formula may be
pay5+pay6

or

(pay6*pay7)*20/100
or
it may take any alphanumeric combinations

Feb 11 '06 #3
<ks***********@gmail.com> wrote:
the formula may be
pay5+pay6

or

(pay6*pay7)*20/100
or
it may take any alphanumeric combinations


Do you know exactly what you need to replace, and that it won't occur
in another form? For instance, if you needed to replace "pay1" with
"5", would you need to cope with:

pay1+repay1

and avoid that becoming

5+re5

?

If not, just use string.Replace:

string changed = original.Replace ("pay1", "5");

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 11 '06 #4
hai,
in c#.net string.replace method is not availbale.

Feb 11 '06 #5
Yes... it most certainly is. Of course, it's String.Replace, not
string.replace, and it's an instance method, so you need an actual
string. You can invoke it exactly as Jon wrote it, assuming that you
have declared a string called "original".

Feb 11 '06 #6
Hmm... this post seems to have gotten lost. Reposting.

There are two ways to look at this problem.

First, perhaps the "variables" in the expression are always named "pay"
followed by a digit. You could use a regular expression to find them,
and then substitute their values for them.

However, this raises the larger question of where are you going to find
their values?

The other way to look at the problem is to decide first where to store
the values. I would suggest a Hashtable, where the variable names are
the keys and the entries are the values. Then all you do is go through
the string, looking for identifiers, and when you find one that is in
the Hashtable, subustitute the corresponding value.

Basically, the algorithm goes like this:

// Fill a Hashtable with variables and corresponding values
Hashtable variables = new Hashtable();
variables["pay1"] = 45.6;
variables["pay6"] = 100.2;
etc.

// Build up a new string with the same expression as the expression
string,
// but with the variables replaced by their values
string expression = "(pay1 * pay6) * 20 / 100";
StringBuilder outExpression = new StringBuilder();
Regex identifierRegex = new Regex("[a-zA-Z][a-zA-Z0-9]*");
int inputIndex = 0;
Match nextIdMatch = identifierRegex.Match(expression, inputIndex);
while (nextIdMatch.Success)
{
string identifier = nextIdMatch.Value;
if (nextIdMatch.Index != inputIndex)
{
// Append everything since the end of the last identifier up to
the start of this identifier
outExpression.Append(expression.Substring(inputInd ex,
nextIdMatch.Index - inputIndex));
}
if (variables.Contains(identifier))
{
// Append the variable value
outExpression.AppendFormat("{0}", variables[identifier]);
}
else
{
// Error: no such variable
}

// Move forward and try to match next identifier
inputIndex = nextIdMatch.Index + nextIdMatch.Length;
nextIdMatch = identifierRegex.Match(expression, inputIndex);
}
if (inputIndex < expression.Length)
{
outExpression.Append(expression.Substring(inputInd ex));
}

// outExpression will now contain "(45.6 * 100.2) * 20 / 100"

WARNING: This code is untested! I make no guarantees that it will work
exactly as written. It's just to give you an idea.

Feb 11 '06 #7
There are two ways to look at this problem.

First, perhaps the "variables" in the expression are always named "pay"
followed by a digit. You could use a regular expression to find them,
and then substitute their values for them.

However, this raises the larger question of where are you going to find
their values?

The other way to look at the problem is to decide first where to store
the values. I would suggest a Hashtable, where the variable names are
the keys and the entries are the values. Then all you do is go through
the string, looking for identifiers, and when you find one that is in
the Hashtable, subustitute the corresponding value.

Basically, the algorithm goes like this:

// Fill a Hashtable with variables and corresponding values
Hashtable variables = new Hashtable();
variables["pay1"] = 45.6;
variables["pay6"] = 100.2;
etc.

// Build up a new string with the same expression as the expression
string,
// but with the variables replaced by their values
string expression = "(pay1 * pay6) * 20 / 100";
StringBuilder outExpression = new StringBuilder();
Regex identifierRegex = new Regex("[a-zA-Z][a-zA-Z0-9]*");
int inputIndex = 0;
Match nextIdMatch = identifierRegex.Match(expression, inputIndex);
while (nextIdMatch.Success)
{
string identifier = nextIdMatch.Value;
if (nextIdMatch.Index != inputIndex)
{
// Append everything since the end of the last identifier up to
the start of this identifier
outExpression.Append(expression.Substring(inputInd ex,
nextIdMatch.Index - inputIndex));
}
if (variables.Contains(identifier))
{
// Append the variable value
outExpression.AppendFormat("{0}", variables[identifier]);
}
else
{
// Error: no such variable
}

// Move forward and try to match next identifier
inputIndex = nextIdMatch.Index + nextIdMatch.Length;
nextIdMatch = identifierRegex.Match(expression, inputIndex);
}
if (inputIndex < expression.Length)
{
outExpression.Append(expression.Substring(inputInd ex));
}

// outExpression will now contain "(45.6 * 100.2) * 20 / 100"

WARNING: This code is untested! I make no guarantees that it will work
exactly as written. It's just to give you an idea.

Feb 11 '06 #8
ya your code is working fine.
now the expression is in string format.to get the value of that
expression, i am using the following snippet.it's throwing error of
input string was not in a correct format because the sring contains + (
- and etc.
am using the following snippet.

double ivalue = Convert .ToDouble(outExpression.ToString());
how to come over this?

Feb 11 '06 #9
Ahh. That's the hard part.

Convert.ToDouble (and the other, similar methods) are only to convert
individual string representations to individual values. So, for
example:

double x = Convert.ToDouble("0.0562");

What you need is an arithmetic expression evaluator. I believe that
VB.NET has an expression evaluator. C# doesn't, yet.

Does anyone know if the expression evaluation method is in the
VB-specific DLL? Is it callable from C#?

Otherwise you have to write your own expression evaluation engine. It's
not too terribly difficult, but it's not easy, either.

Feb 11 '06 #10
In thinking about Jon's reply using String.Replace, it occurred to me
that there's a much easier way to do this.

// Fill a Hashtable with variables and corresponding values
Hashtable variables = new Hashtable();
variables["pay1"] = 45.6;
variables["pay6"] = 100.2;
etc.

string expression = "(pay1 * pay6) * 20 / 100";

// Loop through the hashtable, replacing each variable with its value
string outExpression = expression;
foreach (DictionaryEntry de in variables)
{
string varName = (string)de.Key;
double varValue = (double)de.Value;
outExpression = outExpression.Replace(varName,
varValue.ToString());
}

// outExpression will now contain "(45.6 * 100.2) * 20 / 100"

MUCH easier to read! The only downside is that it doesn't catch
invalid variable names in the expression. Of course, you could always
test outExpression against a regular expression to ensure that it
contained no variable names:

Regex identifierRegex = new Regex("[a-zA-Z][a-zA-Z0-9]*");
Match nextIdMatch = identifierRegex.Match(outExpression);
if (nextIdMatch.Success) { ... still a variable name in the expression
.... }

Feb 11 '06 #11

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

Similar topics

3
by: Greg Yasko | last post by:
Hi. Does anyone know if there's an equivalent of Perl's file::find module in Python? It traverses a directory. I've googled extensively and checked this newsgroup and can't find anything like it...
1
by: Xah Lee | last post by:
suppose you want to do find & replace of string of all files in a directory. here's the code: ©# -*- coding: utf-8 -*- ©# Python © ©import os,sys © ©mydir= '/Users/t/web'
3
by: kittykat | last post by:
Hi, I was wondering if you could help me. I am writing a program in C++, and the problem is, i have very limited experience in this language. I would like my user to enter a specific pattern, and...
14
by: micklee74 | last post by:
hi say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the...
0
by: Xah Lee | last post by:
Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not...
2
by: graphicsxp | last post by:
Hi, How can I open all the files in a directory, which names match a particular string ? Say I have a string like 'a file name to find' and I want to find and open all the files of a given...
14
by: inpuarg | last post by:
I want to find a & character using Regex. But not && How can i manage this in c# Quickfind window ? -------------------------------------------------- ne kadar yaşarsan yaşa sevdiğin kadardır...
0
by: vmysore | last post by:
I am trying to get all the columns selected within a SQL query (including the sub selects). When the code hits matcher.find(). i get the following exception: Exception in thread "main"...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.