2013-10-16 131 views
1

這似乎是一個基本的東西,但我似乎無法繞過正則表達式的我從來沒有真正使用過它們,現在我遇到了一段時間,他們會有用。Java使用和分割字符串使用正則表達式

我看過過去一個小時的例子和過去的問題,但仍然不明白。我的問題是我有一個字符串

"(2 h 9 min from now) | +18.7 feet" 

,我想分成兩個字符串

String a = "2 h 9 min from now"; 

String b = "18.7 feet"; 

我如何使用正則表達式,並使用分割字符串的「正則表達式的'在其他字符串?

到目前爲止,我想出了:

stringx.split("(%s) | +%s \n"); 

stringx.split("(\\w) | +\d.\d feet"); 

但我不知道怎麼弄%S(如果多數民衆贊成甚至右)到正則表達式

之外的字符串
+0

你似乎混淆了'分裂'與正則表達式模式匹配。 –

回答

2

當你想刪除一些字符(在()+),最安全的方法是PatternMatcher類標準的正則表達式匹配:

public static void main (String[] args) { 
    String input= "(2 h 9 min from now) | +18.7 feet"; 
    System.out.println("Input: "+ input); 
    Pattern p = Pattern.compile("\\(([^)]+)\\) \\| \\+(\\d+\\.\\d feet)"); 
    Matcher m = p.matcher(input); 
    String a = null, b = null; 
    if (m.find()) { 
     a = m.group(1); 
     b = m.group(2); 
    } 
    System.out.println("a: "+ a); 
    System.out.println("b: "+ b); 
} 

輸出:

Input: (2 h 9 min from now) | +18.7 feet 
a: 2 h 9 min from now 
b: 18.7 feet 

See online demo here

+0

**注意:**如果您確實想使用String#split(),您可以使用** [此演示中的代碼](http://ideone.com/fSit7Y)**。雖然我不會推薦它,因爲輸入中的細微變化可能會導致意想不到的輸出,並且您的意圖在代碼中不明確(如果維護它的人 - 可能是您自己的將來 - 會更難) 。 – acdcjunior

+0

它仍然看起來很亂,使用正則表達式。它是從api api的bufferedReader中獲取的一段信息。免除字符串。替換字符串.split你會推薦我使用什麼?編輯 - 是的,我知道strickly我應該使用一個XML解析器,但我不能讓一個正常工作,並看到我可以在20行(解析器60行以下)做同樣的事情我想探索使其更多高效並進一步壓縮 – Greg

+0

我仍然建議使用正則表達式(和模式/匹配器類)。我知道它看起來有點亂,但是你的場景真的是正則表達式的用例。其他方法,比如'split()'或'replace()',可能會發送錯誤的消息(它們會使代碼更難讀)。儘管如此,使用正則表達式,您可以使用方法使代碼更簡單。例如,** [檢查此演示](http://ideone.com/4yjO3Z)**。國際海事組織,它非常乾淨。 – acdcjunior

0

您可以使用:

String s = "(2 h 9 min from now) | +18.7 feet"; 
Pattern p = Pattern.compile("^\\(([^)]+)\\)\\s*\\|\\s*\\+(.*)$"); 
Matcher m = p.matcher(s); 
if (m.find())    
    System.out.println(m.group(1) + " :: " + m.group(2)); 

// 2 h 9 min from now :: 18.7 feet 
+0

OP想要擺脫括號和加號。 –

+0

@BoristheSpider:我剛剛注意到,讓我編輯。 – anubhava

0
StringTokenizer stringtokenizer = new StringTokenizer("Your string", "|"); 
while (stringtokenizer.hasMoreElements()) { 
System.out.println(stringtokenizer.nextToken()); 
} 
0

我會這樣做的兩個步驟。

  • 首先,拆分
  • 然後,消毒

例如:

// the original text 
String text = "(2 h 9 min from now) | +18.7 feet"; 
// splitting on the "|" separator 
String[] splitted = text.split("\\|"); 
// printing the raw "split" array 
System.out.println("Raw: " + Arrays.toString(splitted)); 
// iterating over the raw elements of the array 
for (String split: splitted) { 
    // replacing all "raw" strings with the group composed of 
    // word characters in between non word characters (if any) 
    System.out.println(split.replaceAll("^\\W*(.+?)\\W*$", "$1")); 
} 

輸出:

Raw: [(2 h 9 min from now) , +18.7 feet] 
2 h 9 min from now 
18.7 feet 

不是乾淨的解決方案,但它」我會給你一個開始。

相關問題