2012-02-15 121 views
0

如果你有这样的:读字符串中的字符串

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

输出:

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

如何获得之间有什么 “”和“]”?

+0

这取决于..有永远只有一个点?一个反斜杠? – IanNorton 2012-02-15 10:14:37

+0

阅读关于正则表达式 – 2012-02-15 10:15:21

回答

2

如果它总是遵循格式,改变你的代码应该输出w帽子你想要的:

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

简单而有用:)谢谢! – 2012-02-15 10:33:30

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

@Oliver:str在这里是一个数组... – 2012-02-15 10:33:57

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

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

+0

也可以!谢谢! :) – 2012-02-15 10:33:44

0

例如用正则表达式:

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