Solved

C#.net subtract value from string using a regular expression

Posted on 2012-04-05
2
380 Views
Last Modified: 2012-04-05
I'm using the regular expression shown below to find a given string in a text file.  That parts works.  The problem is that I need to subtract 7 from the number in that string in the file.  My code below is currently just writing SE*[d-[7]]*0001~ to the text file instead of updating it.  That makes sense since I put that in the replace portion of the command, but I don't know how to make this work otherwise.  Any ideas?

File.WriteAllText(
                  file,
                  Regex.Replace(File.ReadAllText(file), @"SE\*\d+\*0001~", "SE*[d-[7]]*0001~", RegexOptions.Multiline)
                );

Open in new window


Here is an example of the string I need to subtract 7 from:

SE*2078*0001~

I need it to say:

 SE*2071*0001~
0
Comment
Question by:fcsIT
2 Comments
 
LVL 23

Accepted Solution

by:
wdosanjos earned 500 total points
ID: 37812314
Please try this:
File.WriteAllText(
  file,
  Regex.Replace(File.ReadAllText(file), @"SE\*\d+\*0001~", new MatchEvaluator(this.Subtract), RegexOptions.Multiline)
);

// Add this method to your class
private string Subtract(Match m)
{
	var split = m.Value.Split('*');
	
	split[1] = (int.Parse(split[1]) - 7).ToString();
	
	return split[0] + "*" + split[1] + "*" + split[2];
}

Open in new window

0
 

Author Comment

by:fcsIT
ID: 37812396
I just realized I actually don't have to do this logic.  I will accept your answer as the right one though, you earned it on yesterday's problem!  :)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question