user517406
user517406

Reputation: 13763

Regex value between 2 strings

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

Upvotes: 0

Views: 1524

Answers (4)

Bazzz
Bazzz

Reputation: 26942

Even though the regex answers found on this page are probably good, I took the C# approach to show you an alternative. Note that I typed out every step so it's easy to read and to understand.

//your string
string theString = "d1048_m325";

//chars to find to cut the middle string
char firstChar = 'd';
char secondChar = '_';

//find the positions of both chars
//firstPositionOfFirstChar +1 to not include the char itself
int firstPositionOfFirstChar = theString.IndexOf(firstChar) +1; 
int firstPositionOfSecondChar = theString.IndexOf(secondChar);

//the middle string will have a length of firstPositionOfSecondChar - firstPositionOfFirstChar  
int middleStringLength = firstPositionOfSecondChar - firstPositionOfFirstChar;

//cut!
string middle = theString.Substring(firstPositionOfFirstChar, middleStringLength);

Upvotes: 1

mmix
mmix

Reputation: 6308

You can also use lazy quantifier

d(\d+?)_

Upvotes: 0

Nick
Nick

Reputation: 2478

Alternatively if you want more freedom as to what can be between the d and _:

d([^_]+)

which is

d       # Match d
([^_]+) # Match  (and capture) one or more characters that isn't a _

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

(?<=d)\d+(?=_)

should work (assuming that you're looking for an integer value between d and _):

(?<=d) # Assert that the previous character is a d
\d+    # Match one or more digits
(?=_)  # Assert that the following character is a _

In C#:

resultString = Regex.Match(subjectString, @"(?<=d)\d+(?=_)").Value;

Upvotes: 4

Related Questions