Re: How to get a part of a string using reg exp
- From: Jesse Houwing <jesse.houwing@xxxxxxxxx>
- Date: Thu, 15 Jun 2006 14:13:54 +0200
Marcus Andrén wrote:
On Wed, 14 Jun 2006 13:22:02 -0700, Mike9900
<Mike9900@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
It sounds nice, thanks.
But we do not know the length of the string, nor we know the format. We only want to increment the number embeded inside the string. The string could be like "00vv00fg00021dsd", and so we want to produce "00vv00fg00022dsd.
You have been a little vague, so I can only give an on what you have
given.
Assuming it is is a five digit number and it is the only five digit
number in the string, this should work.
string input = "00vd00asd00999asdkk";
Match m = Regex.Match(input,@"(.*)(\d{5})(.*)");
int val = Convert.ToInt32(m.Groups[2].Value);
val++;
string result = m.Groups[1].Value + val.ToString("00000") +
m.Groups[3].Value;
Console.WriteLine(result);
You can rewrite this using a MatchEvaluator to make it a little easier (and faster):
Regex rx = new Regex(@"\d+");
string s = "00vv00fg00021dsd";
s = rx.Replace(s, new MatchEvaluator(this.Increment));
public string Increment(Match m)
{
int i = int.Parse(m.Value);
i++;
return i.ToString().PadLeft(m.Value.Length, '0') ;
}
This also increments the other two 00 numbers though, but it wouldn't be too hard to exclude those. Using the following MatchEvaluator instead would skip any number that is equal to 0.
public string Increment(Match m)
{
int i = int.Parse(m.Value);
if (i > 0) { i++; }
return i.ToString().PadLeft(m.Value.Length, '0') ;
}
Jesse Houwing
.
- References:
- Re: How to get a part of a string using reg exp
- From: Daniel
- Re: How to get a part of a string using reg exp
- From: Marcus Andrén
- Re: How to get a part of a string using reg exp
- Prev by Date: convert time string to number of seconds
- Next by Date: Re: Use command line option '/keyfile' or appropriate project settings instead of 'AssemblyKeyFile'????
- Previous by thread: Re: How to get a part of a string using reg exp
- Next by thread: Re: How to get a part of a string using reg exp
- Index(es):
Relevant Pages
|