我想从字符串下面提取uid后缀。我正在尝试模式。但是找不到匹配项。
输入:exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt
uid :29510309-5673-4c20-83bd-6d2303c21016
后缀:0
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("exportDocumentInfo_*-*.txt");
String mydata = "exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt
";
Matcher matcher = pattern.matcher(mydata);
if(matcher.matches()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
答案 0 :(得分:1)
将每个*
替换为(.*)
。另外,请删除";
之前的换行符,否则,该程序将无法编译。结果应类似于以下内容:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(final String[] args) {
final Pattern pattern =
Pattern.compile("exportDocumentInfo_(.*)-(.*).txt");
final String mydata =
"exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt";
final Matcher matcher = pattern.matcher(mydata);
if (matcher.matches()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
}
答案 1 :(得分:1)
您需要使用exportDocumentInfo_([\w-]+)-([0-9]+)\.txt
之类的模式,要使用组,需要带括号来捕获内容,并且只允许最后一组中的数字
public static void main(String[] args) {
Pattern pattern = Pattern.compile("exportDocumentInfo_([\w-]+)-([0-9]+)\.txt");
String mydata = "exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt";
Matcher matcher = pattern.matcher(mydata);
if (matcher.matches()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
答案 2 :(得分:1)
这是另一个解决该问题的正则表达式(只需将其替换为您的代码即可):
exportDocumentInfo_(.*)-(.*).txt