473,788 Members | 2,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 8980
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.Replac e ("pay1", "5");

--
Jon Skeet - <sk***@pobox.co m>
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(expressi on, inputIndex);
while (nextIdMatch.Su ccess)
{
string identifier = nextIdMatch.Val ue;
if (nextIdMatch.In dex != inputIndex)
{
// Append everything since the end of the last identifier up to
the start of this identifier
outExpression.A ppend(expressio n.Substring(inp utIndex,
nextIdMatch.Ind ex - inputIndex));
}
if (variables.Cont ains(identifier ))
{
// Append the variable value
outExpression.A ppendFormat("{0 }", variables[identifier]);
}
else
{
// Error: no such variable
}

// Move forward and try to match next identifier
inputIndex = nextIdMatch.Ind ex + nextIdMatch.Len gth;
nextIdMatch = identifierRegex .Match(expressi on, inputIndex);
}
if (inputIndex < expression.Leng th)
{
outExpression.A ppend(expressio n.Substring(inp utIndex));
}

// 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(expressi on, inputIndex);
while (nextIdMatch.Su ccess)
{
string identifier = nextIdMatch.Val ue;
if (nextIdMatch.In dex != inputIndex)
{
// Append everything since the end of the last identifier up to
the start of this identifier
outExpression.A ppend(expressio n.Substring(inp utIndex,
nextIdMatch.Ind ex - inputIndex));
}
if (variables.Cont ains(identifier ))
{
// Append the variable value
outExpression.A ppendFormat("{0 }", variables[identifier]);
}
else
{
// Error: no such variable
}

// Move forward and try to match next identifier
inputIndex = nextIdMatch.Ind ex + nextIdMatch.Len gth;
nextIdMatch = identifierRegex .Match(expressi on, inputIndex);
}
if (inputIndex < expression.Leng th)
{
outExpression.A ppend(expressio n.Substring(inp utIndex));
}

// 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(outEx pression.ToStri ng());
how to come over this?

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

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

double x = Convert.ToDoubl e("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

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

Similar topics

3
7005
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 for Python. I'd be using it in Linux to regularly search for files with a script. Is this a good application for Python or does Perl have more functionality for quick & simple scripting in Linux? Thanks.
1
3729
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
5115
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 I want my program to search a text file for this pattern, and let the user know if this pattern exists or not. So far, i have figured out how to make my prgram read the text file, but i'm not sure how to take the information the user inserts...
14
22582
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 first occurence. I want to know the positions of both "1234" thanks
0
3081
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 want to replace all of them. You need to look at it in a case-by-case basis. What can you do? Answer: emacs.
2
2265
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 directory, which name contains that string. Here is how I open the file of a directory. How can it be modified to
14
2047
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 ömrün :( --------------------------------------------------
0
1545
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" java.lang.StackOverflowError at java.util.regex.Pattern$Branch.match(Pattern.java:4530) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4570) I am not sure where in the regex is causing the inifinite loop. Can anyone shed light on this?
0
9656
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
10175
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...
1
10112
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,...
0
9969
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
5399
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...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
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
3675
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
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...

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.