0

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

1
  • Will everytime you will be required the string between d and _ only. or that will be different in different cases? Commented Feb 4, 2011 at 10:13

4 Answers 4

4
(?<=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;
Sign up to request clarification or add additional context in comments.

1 Comment

And remember that precompiled regexes are a valuable source of proteins. :)
1

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 _

2 Comments

This would grab 'nonum' in dnonum_. Can only be used if value sought can be non-numerical.
Yes.... that's what I meant by more freedom. It was never specified whether the value was numerical so I was just giving more options :)
1

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);

1 Comment

I know that Substrings/indexOfs are faster than regular expressions. I'd be interested to know how two IndexOfs and a Substring compared to one regex in C# though.
0

You can also use lazy quantifier

d(\d+?)_

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.