2011-02-04 237 views
0

如何獲取2個字符串之間的值?我有一個格式爲d1048_m325的字符串,我需要得到d和_之間的值。這是如何在C#中完成的?2個字符串之間的正則表達式值

感謝,

邁克

+0

是否每次需要d和_之間的字符串。或者在不同情況下會有所不同? – 2011-02-04 10:13:22

回答

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

應該工作(假設你正在尋找d_之間的整數):

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

在C#:

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

請記住,預編譯的正則表達式是蛋白質的重要​​來源。 :) – 2011-02-04 10:18:13

+0

優秀...感謝您的解釋! – user517406 2011-02-04 11:12:45

1

或者,如果你想要更多的自由,什麼可以是d和_之間:

d([^_]+) 

這是

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

這將在dnonum_中抓取'nonum'。只有在尋求的價值可以是非數值時才能使用。 – mmix 2011-02-04 10:24:24

0

您還可以使用惰性限定符

d(\ d +?)_

1

儘管在本頁找到了正則表達式的答案可能是好的,我採用了C#方法來向你展示一個替代方案。請注意,我輸入了每一步,因此很容易閱讀和理解。

//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); 
相關問題