使用正则表达式获取第二个给定字符之前的所有内容
本文关键字:字符 正则表达式 获取 第二个 | 更新日期: 2023-09-27 18:08:51
我有一个类似的字符串列表
[ABC].[XXX].sdfnwoaenwaf
[ABC].[XXX].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[ABC].[XX1].sdfnwoaenwaf
[AB1].[XX3].sdfnwoaenwaf
[AB2].[XX1].sdfnwoaenwaf
如何在第二个点之前获取所有内容?例如第一个的CCD_ 1。
(.*)'.
是您需要的正则表达式。您可以在上进行测试http://regexhero.net/tester/
您可以尝试regex,或者使用String类的LastIndexOf
方法或String类的Split
方法。
Regex
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));
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]
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]);
}