如何获取2个字符串之间的值?我有一个格式为d1048_m325的字符串,我需要得到d和_之间的值。这是如何在C#中完成的?
谢谢,
迈克答案 0 :(得分: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;
答案 1 :(得分:1)
或者,如果您想要更自由地了解d和_之间的内容:
d([^_]+)
是
d # Match d
([^_]+) # Match (and capture) one or more characters that isn't a _
答案 2 :(得分: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);
答案 3 :(得分:0)
您也可以使用延迟量词
d(\ d +?)_