【发布时间】:2015-02-28 13:27:18
【问题描述】:
我创建了一个小函数来捕获字符串之间的字符串。
public static string[] _StringBetween(string sString, string sStart, string sEnd)
{
if (sStart == "" && sEnd == "")
{
return null;
}
string sPattern = sStart + "(.*?)" + sEnd;
MatchCollection rgx = Regex.Matches(sString, sPattern);
if (rgx.Count < 1)
{
return null;
}
string[] matches = new string[rgx.Count];
for (int i = 0; i < matches.Length; i++)
{
matches[i] = rgx[i].ToString();
//MessageBox.Show(matches[i]);
}
return matches;
}
但是,如果我这样调用我的函数:_StringBetween("[18][20][3][5][500][60]", "[", "]");
它会失败。一种方法是如果我更改此行string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd;
但是我不能,因为我不知道字符是括号还是单词。
对不起,如果这是一个愚蠢的问题,但我找不到类似的搜索。
【问题讨论】:
-
你到底想返回什么,一个字符串数组 "[18], [20], [3]..." 或者一个字符串数组 "18, 20, 3... “?该代码将返回第一个,但它的命名就好像您希望它返回后者一样。