Java正则表达式问题与组

时间:2011-07-18 04:20:50

标签: java regex

我希望能够使用组使用单个正则表达式解析字符串下面的字符串吗?短划线和数字之间可能有也可能没有单个/多个空格。

输入字符串示例:

"0.4 - 1.2 Mathematics"
"0.7-1.3 Physics"
"0.3-    0.7      Chemistry"
"4.5 Biology"
"2 Calculus"

group(1) -> lowGrade -> Float
group(2) -> highGrade -> Float (if exists)
group(3) -> class -> String

你能帮助正则表达式吗? 感谢

3 个答案:

答案 0 :(得分:1)

String s = "Mathematics 0.4 - 1.2";

Matcher m = Pattern.compile("(.*?) *([0-9.]+) *(- *([0-9.]*))?").matcher(s);
if(m.matches()){
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(4));
}

答案 1 :(得分:1)

所以这是你的工作解决方案,如果“highGrade”不可用,则第二组是NULL

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{
    public static void main(String[] args)
    {
        String Text = "0.4 - 1.2 Mathematics";
        Pattern p = Pattern.compile("^" + // Match the start of the string
                "(\\d+(?:\\.\\d+)?)" + // Match the first float, the fraction is optional, (?:) is a non capturing group
                "(?:\\s*-\\s*" + // Match the whitespace and the - . This part including the following float is optional
                "(\\d+(?:\\.\\d+)?))?" + // Match the second float, because of the ? at the end this part is optional
            "\\s*(.*)" + // Match the whitespace after the numbers and put the rest of the chars in the last capturing group
            "$"); // Match the end of the string

        Matcher m = p.matcher(Text);

        if (m.matches()) {
            System.out.println(m.group(1));
            System.out.println(m.group(2));
            System.out.println(m.group(3));
        }
    }
}

答案 2 :(得分:0)

你试过这个:

String s = "Mathematics 0.4 - 1.2";
pattern = Pattern.compile("([^\d\.\s]+)\b\s+(\d+\.\d+)\D*(\d+\.\d+)?");
matcher = pattern.matcher(s);
if (matcher.matches()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
}