C#获取两个相同字符之间的值

时间:2016-05-09 10:51:01

标签: c# regex character

通常,我们可以轻松获得两个字符之间的String值。我的问题是,如何获得两个相同字符之间的值。

例如:

String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";

在此示例中,如何从整个字符串中提取值9367119

我使用的解决方案不起作用,因为9367119在其右侧和左侧具有相同的/个字符。

这是我到目前为止所拥有的:

这适用于左右两个字符不相同的值。例如:/ dog \我可以轻松地用我的解决方案替换/\

public static string Between(string full_value, string a, string b)
{
        int posA = full_value.IndexOf(a);
        int posB = full_value.LastIndexOf(b);
        if (posA == -1)
        {
            return "";
        }
        if (posB == -1)
        {
            return "";
        }
        int adjustedPosA = posA + a.Length;
        if (adjustedPosA >= posB)
        {
            return "";
        }
        return full_value.Substring(adjustedPosA, posB - adjustedPosA);
    }

3 个答案:

答案 0 :(得分:3)

你可以Split获得相关部分:

string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
string[] sp = s.Split('/');
Console.WriteLine(sp[4]);

IdeOne demo

答案 1 :(得分:1)

使用以下正则表达式:

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

String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";
var matches = Regex.Matches(full_value, @"(?<=/)\d+(?=/)");

答案 2 :(得分:1)

尝试这种方式使用Split

 string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
    string[] sps = s.Split('/');
    foreach(string sp in sps ){
     if(sp =="9367119"){
       Console.WriteLine(sp);
      }
    }