2011-07-18 50 views
0

我想使用組來使用單個正則表達式解析字符串下面的內容嗎?短劃線和數字之間可能有或沒有單個/多個空格。關於組的Java正則表達式問題

輸入字符串的例子:

 
"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 

你能和正則表達式的幫助嗎? 感謝

回答

1

因此,這裏是你的工作的解決方案,如果「高誠」無法使用第二組是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)); 
     } 
    } 
} 
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)); 
} 
+0

謝謝你的回答,我想你在我編輯問題之前回答,我很抱歉,這是我的錯。 – aug70co

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)); 
} 
+0

謝謝你的回答,我想你在我編輯這個問題之前回答了,我很抱歉,這是我的錯。 – aug70co