简体   繁体   English

2个字符串之间的正则表达式值

[英]Regex value between 2 strings

How do I get the value in between 2 strings? 如何获取2个字符串之间的值? I have a string with format d1048_m325 and I need to get the value between d and _. 我有一个格式为d1048_m325的字符串,我需要获取d和_之间的值。 How is this done in C#? 如何在C#中完成?

Thanks, 谢谢,

Mike 麦克风

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

should work (assuming that you're looking for an integer value between d and _ ): 应该可以工作(假设您正在寻找d_之间的整数值):

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

In C#: 在C#中:

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

Alternatively if you want more freedom as to what can be between the d and _: 或者,如果您想在d和_之间有更多自由,请执行以下操作:

d([^_]+)

which is 这是

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

Even though the regex answers found on this page are probably good, I took the C# approach to show you an alternative. 即使在此页面上找到的正则表达式答案可能很好,我还是采用C#方法向您展示了另一种方法。 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);

You can also use lazy quantifier 您也可以使用惰性量词

d(\\d+?)_ d(\\ d +?)_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM