【问题标题】:Extract file extension from String using regex使用正则表达式从字符串中提取文件扩展名
【发布时间】:2018-03-09 19:14:25
【问题描述】:

我有以下字符串:

"data:audio/mp3;base64,ABC..."

我正在从中提取文件扩展名(在本例中为 "mp3")。

字符串因文件类型而异。一些例子:

"data:image/jpeg;base64,ABC..."
"data:image/png;base64,ABC..."
"data:audio/wav;base64,ABC..."
"data:audio/mp3;base64,ABC..."

这是我的做法:

public class Test {

    private static final String BASE64_HEADER_EXP = "^data:.+;base64,";

    private static final Pattern PATTERN_BASE64_HEADER = Pattern.compile(BASE64_HEADER_EXP);

    private String data;

    private String fileName;

    public String getFileName() {
        Matcher base64HeaderMatcher = PATTERN_BASE64_HEADER.matcher(data);
        return String.format("%s.%s", getFilenameWithoutExtension(), getExtension(base64HeaderMatcher));
    }

    private String getFilenameWithoutExtension() {
        return fileName.split("\\.")[0];
    }

    private String getExtension(Matcher base64HeaderMatcher) {
        if (base64HeaderMatcher.find()) {
            String base64Header = base64HeaderMatcher.group(0);
            return base64Header.split("/")[1].split(";")[0];
        }
        return fileName.split("\\.")[1];
    }

}

我想要的是一种无需像上面那样拆分和访问数组位置的方法。也许使用正则表达式提取扩展名。

我可以在RegExr 网站上使用这个表达式:

(?<=^data:.*/)(.*)(?=;)

但是,当尝试在 Java 上使用相同的正则表达式时,我收到错误 "Require that the characters immediately before the position do",因为显然 Java 不支持后向内的重复:

【问题讨论】:

    标签: java regex


    【解决方案1】:

    使用捕获组怎么样?

    private static final String BASE64_HEADER_EXP = "^data:[^/]+/([^;]+);base64,";
    

    这样您就可以使用base64HeaderMatcher.group(1) 并获取文件类型。

    【讨论】:

      【解决方案2】:

      对于您提供的示例应该这样做:

      (?<=data:)(?:[A-z]+)/(.*?);
      

      解释:

      正向回顾

      (?<=data:)
      

      非捕获组占imageaudio

      (?:[A-z]+)
      

      从字面上匹配/,为文件扩展名捕获组,从字面上匹配;

      /(.*?);
      

      【讨论】:

        【解决方案3】:

        “Java 中的字符串内置了对正则表达式的支持。字符串有四种内置的正则表达式方法,即matches()、split())、replaceFirst() 和replaceAll() 方法。” -http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

        使用此信息我们可以快速创建一个正则表达式并针对我们的字符串进行测试。

        //In regex each set of () represents a capture field which can later be 
        //referenced with $1, $2 etc..
        //The below regex breaks the string into four fields 
        
        string pattern="(^data:)(\\w+?/)(\\w+?)(;.*$)";
        
        //First Field
        //This field matches the start of a line (^) followed by "data:"
        
        //Second Field
        //This matches any wordCharacter (\\w), one or more (+) followed by a "/"
        // the "?" symbol after the + means reluctantly match, match as few 
        //characters 
        //as possible. this field will effectively capture a seriece of letters 
        //followed by a slash
        
        //Third Field
        //This is the field we want to capture and we will reference with $3
        //it matches any wordCharacter(\\w), one or more reluctantly
        
        //Fourth Field
        //This captures the rest of the string including the ";"
        
        
        //Now to extract the extension from this test string
        
        string test="data:image/jpeg;base64,ABC...";
        string testExtension="";
        
        //Replace the contents of testExtension with the 3rd capture field of 
        //our regex pattern applied to our test string like so
        
        testExtension = test.replaceAll(pattern, "$3");
        
        //This invokes the String class replaceAll() method 
        
        //And now our string testExtension should contain "jpeg"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-18
          • 2014-10-17
          • 2023-03-29
          相关资源
          最近更新 更多