2015-02-11 70 views
0

我在java中使用正則表達式來從我的大學的房間列表中獲取特定的輸出。在Java中的特殊字符後的正則表達式

從列表甲出氣看起來像這樣:

  • (A55:G260)LABORATORIUM 260
  • (A55:G292)Grupperom 292
  • (A55:G316)Grupperom 316
  • ( A55:G366)Grupperom 366
  • (HDS:弗羅伊恩)前往Fløyen(附錄)
  • (ODO:PC-Stue酒店)Pulpakammeret(PC-Stue酒店)
  • (SALEM:KONF)Konferanserom

我想獲取冒號和括號之間的值。

我使用目前的正則表達式是:

pattern = Pattern.compile("[:]([A-Za-z0-9ÆØÅæøå-]+)"); 
matcher = pattern.matcher(room.text()); 

我已經包括ÆØÅ,因爲一些房間中都有挪威字母。

不幸的是,正則表達式包括建築規範也輸出(例如「A55」)......出來像這樣:

A55 
A55 
A55 
:G260 
:G292 
:G316 

如何解決這個任何想法?

+0

在什麼輸出?你只顯示正則表達式,但你如何實際使用匹配器來檢索結果?再加上這個問題。 – eis 2015-02-11 13:31:33

回答

0

你可以嘗試一個正則表達式是這樣的:

public static void main(String[] args) { 
    String s = "(HDS:FLØYEN) Fløyen (appendix)"; 
    // select everything after ":" upto the first ")" and replace the entire regex with the selcted data 
    System.out.println(s.replaceAll(".*?:(.*?)\\).*", "$1")); 
    String s1 = "ODO:PC-STUE) Pulpakammeret (PC-stue)"; 
    System.out.println(s1.replaceAll(".*?:(.*?)\\).*", "$1")); 
} 

O/P:

FLØYEN 
PC-STUE 
1

的問題是不是你的正則表達式。您需要參照組(1)獲得比賽結果。

while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

但是,您可能會考慮使用否定字符類。

pattern = Pattern.compile(":([^)]+)"); 
+0

太棒了!它的工作,非常感謝你:) – Gaute 2015-02-11 13:41:59

0

可與String Opreations嘗試如下,

String val = "(HDS:FLØYEN) Fløyen (appendix)"; 

if(val.contains(":")){ 

    String valSub = val.split("\\s")[0]; 
    System.out.println(valSub); 

    valSub = valSub.substring(1, valSub.length()-1); 

    String valA = valSub.split(":")[0]; 
    String valB = valSub.split(":")[1]; 

    System.out.println(valA); 
    System.out.println(valB); 

} 

輸出:

(HDS:FLØYEN) 
HDS 
FLØYEN 
0

進口java.util.regex.Matcher中; import java.util.regex.Pattern;

類測試 { 公共靜態無效主要(字符串ARGS []){

// String to be scanned to find the pattern. 
    String line = "(HDS:FLØYEN) Fløyen (appendix)"; 
    String pattern = ":([^)]+)"; 

    // Create a Pattern object 
    Pattern r = Pattern.compile(pattern); 

    // Now create matcher object. 
    Matcher m = r.matcher(line); 
    while (m.find()) { 
    System.out.println(m.group(1)); 
} 

} }