我想从一个字符串中获取返回参数:
Lorem ipsum dolor sit amet, %param% consectetur adipiscing elit. Ut placerat risus vitae augue vestibulum imperdiet. Nullam ac urna pellentesque purus hendrerit convallis. Morbi bibendum augue sed mi faucibus, sit amet scelerisque augue interdum. Aenean iaculis lacus ut sapien imperdiet mollis.
我试图使用:
texte.Split(new char[] {'%'});
它只是拆分了我的文本,如何用开始字符和结束字符分割?
答案 0 :(得分:4)
以下正则表达式应该有所帮助:
var regex = new Regex(@"%(?<param>.*?)%");
var match = regex.Match("Lorem ipsum dolor sit amet, %param% consectetur adipiscing elit. Ut placerat risus vitae augue vestibulum imperdiet. Nullam ac urna pellentesque purus hendrerit convallis. Morbi bibendum augue sed mi faucibus, sit amet scelerisque augue interdum. Aenean iaculis lacus ut sapien imperdiet mollis.");
if(match.Success)
{
string result = match.Groups["param"].Value;
}
如果有多个匹配项,以下代码将有所帮助:
string subject = "Lorem ipsum dolor sit amet, %param% consectetur %454% adipiscing elit. Ut placerat risus vitae augue vestibulum imperdiet. Nullam ac urna pellentesque purus hendrerit convallis. Morbi bibendum augue sed mi faucibus, sit amet scelerisque augue interdum. Aenean iaculis lacus ut sapien imperdiet mollis.";
var matches = Regex.Matches(subject, @"%(?<param>.*?)%");
foreach (Match match in matches)
{
string result = match.Groups["param"].Value;
}
答案 1 :(得分:1)
这应该有用..
string str = "Lorem ipsum dolor sit amet, %param% consectetur adipiscing elit. Ut placerat risus vitae augue vestibulum imperdiet. Nullam ac urna pellentesque purus hendrerit convallis. Morbi bibendum augue sed mi faucibus, sit amet scelerisque augue interdum. Aenean iaculis lacus ut sapien imperdiet mollis.";
var param = str.Substring(str.IndexOf('%') + 1, str.IndexOf('%', (str.IndexOf('%') + 1)) - str.IndexOf('%') - 1);
答案 2 :(得分:0)
你可以使用foreach
循环来完成它,虽然它可能效率不高,具体取决于字符串的长度。
string input = "Lorem ipsum dolor sit amet, %param% consectetur adipiscing elit. Ut placerat risus vitae augue vestibulum imperdiet. Nullam ac urna pellentesque purus hendrerit convallis. Morbi bibendum augue sed mi faucibus, sit amet scelerisque augue interdum. Aenean iaculis lacus ut sapien imperdiet mollis."
StringBuilder param = new StringBuilder();
List<string> params = new List<string>();
bool writingParam = false;
foreach(char c in input) {
if(!writingParam && c == '%') {
writingParam = true;
}
else if(writingParam) {
if(c != '%') {
param.Append(c);
}
else {
params.Add(param.ToString());
param = new StringBuilder();
writingParam = false;
}
}
}
您将最终得到包含%
中包含的所有字符串的字符串列表。
答案 3 :(得分:0)
如果字符串中只有一个%param%,您可以使用indexOf和lastIndexOf
找到它int len = input.Length;
int pos1 = input.IndexOf("%");
int pos2 = input.LastIndexOf("%");
string response = "";
if (pos1 != -1 && pos2 != -1 && (pos2 >= pos1))
{
response = s.Substring(pos1 + start.Length, pos2 - pos1 - start.Length);
}