首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正则表达式-如何从字符串ABC_ABC12345_ABC_ABC.txt中仅保留ABC12345,有时它可以是ABC12345_ABC.txt

正则表达式-如何从字符串ABC_ABC12345_ABC_ABC.txt中仅保留ABC12345,有时它可以是ABC12345_ABC.txt
EN

Stack Overflow用户
提问于 2018-10-17 22:26:23
回答 3查看 62关注 0票数 0

正则表达式-如何从字符串ABC_ABC12345_ABC_ABC.txt中仅保留ABC12345,有时它可以是ABC12345_ABC.txt

EN

回答 3

Stack Overflow用户

发布于 2018-10-17 22:32:33

您可以RegEx搜索模式^.*_(\w+\d+)_.*$以返回所需的匹配项。此模式假定所需的匹配项包含在下划线中,具有一对多字符的字母数字前缀,并以一对多数字结束。

更新:修改了模式,允许匹配可以在字符串的开头,而不是在前面加上下划线:^(.*_|)(\w+\d+)_.*$。在此模式中,您可能希望捕获第二个匹配。

票数 0
EN

Stack Overflow用户

发布于 2018-10-17 22:39:52

在不太了解匹配条件的情况下(例如,它只是数字、通过下划线的任何分隔符或其他?),我会说这可能会起作用:

代码语言:javascript
复制
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;

如果您不需要它来替换原始字符串(您只需要结果),只需将其放入一个单独的变量。

票数 0
EN

Stack Overflow用户

发布于 2018-10-19 04:39:27

代码语言:javascript
复制
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");
        }
    }
}

测试结束后

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52857289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档