如何获取两个字符串之间的值?我有一个格式为d1048_m325的字符串,我需要获取d和_之间的值。在C#中如何做到这一点?
谢谢,
麦克
发布于 2011-02-04 10:11:43
(?<=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;
发布于 2011-02-04 10:15:46
或者,如果您希望在d和_之间有更大的自由度
d([^_]+)
这就是
d # Match d
([^_]+) # Match (and capture) one or more characters that isn't a _
发布于 2011-02-04 10:28:55
尽管在此页面上找到的正则表达式答案可能很好,但我采用了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);
https://stackoverflow.com/questions/4896757
复制相似问题