473,395 Members | 1,986 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,395 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 8940
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.