Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex question

Status
Not open for further replies.

ccmike

Programmer
Joined
Feb 4, 2011
Messages
1
Location
GB
Hi,

How do I get the value in between 2 strings? I have a string with format d1048_m325 and I need to get the value between d and _. How is this done in C#?


Thanks,


Mike
 
Regex commands are located in the system.text.regularexpressions namespace.
off the top of my head it would look something like this
Code:
var input = "d1048_m325";
//^d\d+_ -> the first letter is d followed by 1 or more digits and then an underscore.
var match = Regex.Match(input, "^d\d+_");
if(match.Success == false) 
{
   return null;
}
var finalMatch = Regex.Match(match.Value, "\d+");
return int.Parse(finalMatch.Value);
if you know the number will be exactly 4 digits you can use this
Code:
var input = "d1048_m325";
//^d\d+_ -> the first letter is d followed by 4 digits and then an underscore.
var match = Regex.Match(input, "^d\d{4}_");
if(match.Success == false) 
{
   return null;
}
//the value is 'd1048_'. take the next 4 characters starting at the 2nd character
var result = match.Value.SubString(1, 4);
return int.Parse(result);

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top