读取字符串中的字符串

时间:2012-02-15 10:11:20

标签: c# string

如果你有这个:

foreach(string n in txtList)
{
    Console.WriteLine(n);
}

输出:

[HKEY_Something_Something\.abc]
[HKEY_Something_Something\.defg]
[HKEY_Something_Something\.ijklmn]

我如何得到“。”之间的内容。和“]”?

6 个答案:

答案 0 :(得分:2)

如果它始终遵循该格式,将代码更改为此应输出您想要的内容:

foreach(string n in txtList)
{
  int startindex = n.IndexOf(@"\.") + 2;
  Console.WriteLine(n.Substring( startindex, n.Length-startindex-1));
}

答案 1 :(得分:0)

尝试

 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));
        }
    }

答案 2 :(得分:0)

您可以使用正则表达式:

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

答案 3 :(得分:0)

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);

答案 4 :(得分:0)

简单回答:

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));

更复杂的答案:使用正则表达式。

答案 5 :(得分:0)

例如使用RegEx:

  Match match = Regex.Match(n, @"\.(.*)\]");  
  string result = match.Groups[1].Value;