2011-02-04 136 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); 
相关问题