0

我有一个字符串列表,例如

[ABC].[XXX].sdfnwoaenwaf
[ABC].[XXX].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[AB1].[XX3].sdfnwoaenwaf
[AB2].[XX1].sdfnwoaenwaf

我怎样才能在第二个点之前得到所有东西?例如[ABC].[XXX]第一个。

4

4 回答 4

2

(.*)\.是您需要的正则表达式。您可以在http://regexhero.net/tester/上进行测试

于 2013-04-12T05:39:11.337 回答
1

您可以尝试正则表达式或使用LastIndexOfString 类的Split方法或 String 类的方法。

正则表达式

var toMatch = "[ABC].[XXX].sdfnwoaenwaf";

var pattern = new Regex("(.*?\\..*?)(:?\\.)");

var beforeSecondDot = pattern.Match(toMatch);

var stringBeforeSecondDot = beforeSecondDot.Groups[1].Value;

String.LastIndexOf

var toMatch = "[ABC].[XXX].sdfnwoaenwaf";

var indexOfLastDot = toMatch.LastIndexOf('.');

var beforeSecondDot = toMatch.Substring(0, indexOfLastDot);

字符串拆分

var toMatch = "[ABC].[XXX].sdfnwoaenwaf";

var parts = toMatch.Split('.');

var beforeSecondDot = String.Join(".", parts.Take(2));
于 2013-04-12T05:45:31.753 回答
1
string x = "[AB2].[XX1].sdfnwoaenwaf";

Regex regex = new Regex("([^.]+\\.[^.]+)\\.");
Match match = regex.Match(x);
if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
}

输出:

[AB2].[XX1]
于 2013-04-12T05:49:03.500 回答
1
List<string> finalStrings = new List<string>();
List<string> strings = new List<string>();
strings.Add("[ABC].[XXX].sdfnwoaenwaf");
strings.Add("[ABC].[XXX].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");
strings.Add("[ABC].[XX3].sdfnwoaenwaf");
strings.Add("[ABC].[XX1].sdfnwoaenwaf");

foreach (var item in strings)
{
     Regex rex = new Regex("(.*)\\.");
     string[] y = rex.Split(item);
     finalStrings.Add(y[1]);
}
于 2013-04-12T05:54:40.010 回答