正则表达式-如何从字符串ABC_ABC12345_ABC_ABC.txt中仅保留ABC12345,有时它可以是ABC12345_ABC.txt
发布于 2018-10-17 22:32:33
您可以RegEx搜索模式^.*_(\w+\d+)_.*$以返回所需的匹配项。此模式假定所需的匹配项包含在下划线中,具有一对多字符的字母数字前缀,并以一对多数字结束。
更新:修改了模式,允许匹配可以在字符串的开头,而不是在前面加上下划线:^(.*_|)(\w+\d+)_.*$。在此模式中,您可能希望捕获第二个匹配。
发布于 2018-10-17 22:39:52
在不太了解匹配条件的情况下(例如,它只是数字、通过下划线的任何分隔符或其他?),我会说这可能会起作用:
string test = "ABC_ABC12345_ABC_ABC.txt";
Regex rx = new Regex(@"ABC\d+");
Match m = rx.Match(test);
if (m.Success)
test = m.Groups[0].Value;如果您不需要它来替换原始字符串(您只需要结果),只需将其放入一个单独的变量。
发布于 2018-10-19 04:39:27
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string string1 = "ABC_ABC12345_ABC_ABC.txt";
Regex s1 = new Regex(@"\w{3}\d{5}");
//if just for capital letter and only three characters and five numbers use: Regex s2 = new Regex(@"[A-Z]{3}\d{5}");
//if the number of characters "capital letter" and numbers does not matter use: Regex s2 = new Regex(@"[A-Z]+\d+");
//if the number of characters "capital and small letter" and numbers does not matter use: Regex s2 = new Regex(@"[A-Za-z]+\d+");
Regex s2 = new Regex(@"\w{3}\d{5}\w{8}\.\w{3}");
//if just for capital letter and only three characters and five numbers use: Regex s2 = new Regex(@"[A-Z]{3}\d{5}_[A-Z]{3}_[A-Z]{3}\.\w{3}");
//if the number of characters "capital letter" and numbers does not matter use: Regex s2 = new Regex(@"[A-Z]+\d+_[A-Z]+_[A-Z]+\.\w{3}");
//if the number of characters "capital and small letter" and numbers does not matter use: Regex s2 = new Regex(@"[A-Za-z]+\d+_[A-Za-z]+_[A-Za-z]+\.\w{3}");
Match m1 = s1.Match(string1);
Match m2 = s2.Match(string1);
if (m1.Success){
String result = m1.ToString();
Console.WriteLine(result);
}
else if(m2.Success){
String result = m2.ToString();
Console.WriteLine(result);
}
else{
Console.WriteLine("No match");
}
}
}测试结束后

我已经注释了第一个条件,以验证第二个条件

https://stackoverflow.com/questions/52857289
复制相似问题