如何在c#中返回子字符串的值
本文关键字:字符串 返回 | 更新日期: 2023-09-27 18:17:30
我想从字符串中获取参数:
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[] {'%'});
它只是分割我的文本,我怎么分割开始字符和结束字符?
下面的正则表达式应该有帮助:
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;
}
应该可以。
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);
您可以使用foreach
-loop来实现它,尽管它可能不是很有效,这取决于字符串的长度。
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;
}
}
}
您将得到一个包含%
中包含的所有字符串的字符串列表。
如果字符串中只有一个%参数%,你可以使用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);
}