【发布时间】:2020-05-19 18:12:33
【问题描述】:
我想将一些文本传递给一个班级并让它返回一个数字和该文本的等级。
现在,如果没有给出分数,班级应该返回数字和分数,即 0.0
我现在的问题是我正在使用正则表达式(组)提取该数据。 一旦 Pattern 与整个文本不匹配,我就无法再检索数字了。
一个没有成绩的文本输入示例是:
2456272 Max Mustermann 20.02.1968
2456272 would be the number
A grade would be at the very end of the input
到目前为止我的代码:
static final String REGEX = "^(?<studentnumber>\\d{7})" // start with student number
+ ".*" // anything in between
+ "\\s+" // separated by at least one space
+ "(?<grade>10(\\.0)?|\\d([.,]\\d)?)" // 10(.0)? or one digit and optionally comma or period followed one digits.
+ "$"; // and nothing else
private static final Pattern PATTERN = Pattern.compile(REGEX);
private final Matcher matcher;
/**
* Construct a GradeFilter from a string (line).
*
* @param line to read
*/
public GradeCapture(String line) {
matcher = PATTERN.matcher(line);
matcher.matches();
}
/**
* Create a tuple. Use AbstractMap. SimpleEntry as implementing class.
* @return the tuple.
*/
public AbstractMap.SimpleEntry<Integer, Double> getResult() {
if (hasResult()) {
return new AbstractMap.SimpleEntry<>(studentId(), grade());
}
return new AbstractMap.SimpleEntry<>(studentId(), 0D);
}
/**
* Does the line contain the required data?
* @return whether there is a match
*/
public boolean hasResult() {
Integer studentId = studentId();
Double grade = grade();
if (studentId == null || grade == null) {
return false;
}
return true;
}
//</editor-fold>
/**
* Get the grade, if any.
*
* @return the grade or null
*/
public Double grade() {
try {
String grade = matcher.group("grade");
grade = grade.replaceAll(",", ".");
return Double.parseDouble(grade);
} catch (Exception e) {
return null;
}
}
/**
* Get the student id, if any.
*
* @return the student id or null when no match.
*/
public Integer studentId() {
try {
String studentnumber = matcher.group("studentnumber");
return Integer.parseInt(studentnumber);
} catch (Exception e) {
return null;
}
}
我只想在部分匹配失败时检索匹配器组“studentnumber”。
【问题讨论】:
-
去掉开头的
^和结尾的$。它们分别匹配您输入的开始和结束。 -
请edit您的问题并发布一个不包含成绩的示例。
-
遗憾的是,这不起作用,“studentnumber”组仍然为空
-
1) 如果失败,请执行您现在的操作:2) 运行此正则表达式以获取数字:"^(?
\\d{7})"; -
我确实编辑了示例。
标签: java regex regex-group