读取字符串中的字符串
本文关键字:字符串 读取 | 更新日期: 2023-09-27 18:24:34
如果你有这个:
foreach(string n in txtList)
{
Console.WriteLine(n);
}
输出:
[HKEY_Something_Something'.abc]
[HKEY_Something_Something'.defg]
[HKEY_Something_Something'.ijklmn]
如何获取介于"."answers"]"之间的内容?
如果它总是遵循这种格式,那么将代码更改为这种格式应该会输出您想要的内容:
foreach(string n in txtList)
{
int startindex = n.IndexOf(@"'.") + 2;
Console.WriteLine(n.Substring( startindex, n.Length-startindex-1));
}
尝试
foreach(string n in txtList)
{
string str[] = n.Split('.');
if (str.Length > 0)
{
string s = str[str.Length-1];
Console.WriteLine(s.Substring(0, s.Length-1));
}
}
您可以使用正则表达式:
var s = @"[HKEY_Something_Something'.abc]";
var result = Regex.Match(s, @"(?<='.)[^]]*(?=]$)")
// result == "abc"
正则表达式的简短解释:
(?<='.) - preceded by a dot
[^]]* - anything which isn't a ']'
(?=]$) - followed by a ']' and the end of the string
var per = n.IndexOf("."); // may need to add +1 to get past . index.
var len = n.IndexOf("]") - per - 1;
var val = n.Substring(per, len);
简单答案:
int dotPosition = n.LastIndexOf(".") + 1; // +1 because we start AFTER the dot.
int bracketPosition = n.LastIndexOf("]"); // can do "n.Length - 2" too.
Console.WriteLine(n.Substring(dotPosition, bracketPosition - dotPosition));
更复杂的答案是:使用正则表达式。
例如RegEx:
Match match = Regex.Match(n, @"'.(.*)']");
string result = match.Groups[1].Value;