[英]Regex catch string between strings
我创建了一个小函数来捕获字符串之间的字符串。
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;
但是我不能,因为我不知道该字符是括号还是单词。
抱歉,如果这是一个愚蠢的问题,但是我找不到类似的搜索内容。
一种方式是,如果我更改此行字符串
sPattern = "\\\\" + sStart + "(.*?)" + "\\\\" + sEnd;
但是我不能,因为我不知道该字符是括号还是单词。
您可以通过调用Regex.Escape
来转义所有元字符:
string sPattern = Regex.Escape(sStart) + "(.*?)" + Regex.Escape(sEnd);
这将导致对sStart
和sEnd
的内容进行字面解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.