我想从该URL中提取一些字符串
https://s3-ap-southeast-1.amazonaws.com/mtpdm/2019-06-14/12-14/1001_1203_20190614120605_5dd404.jpg
我想提取2019-06-14,如何使用Java提取?
答案 0 :(得分:2)
使用正则表达式来获取日期 2019-06-14
,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractDateFromURL {
public static void main(String []args) {
String URL = "https://s3-ap-southeast-1.amazonaws.com/mtpdm/2019-06-14/12-14/1001_1203_20190614120605_5dd404.jpg";
Pattern pattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{1,2})");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(1)); // Do what you need to do with the result
}
}
}
输出
2019-06-14
要获取12-14
,您可以使用以下正则表达式,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractDateFromURL {
public static void main(String []args){
String URL = "https://s3-ap-southeast-1.amazonaws.com/mtpdm/2019-06-14/12-14/1001_1203_20190614120605_5dd404.jpg";
Pattern pattern = Pattern.compile("/(\\d{1,2}-\\d{1,2}-\\d{4}|\\d{1,2}-\\d{1,2})");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
输出
12-14