2011-05-12 51 views
0

我在Arraylist中有一組字符串。帶數字的java字符串

我想刪除所有字符串,只有數字 也是這樣的字符串:(0.75%),$ 1.5 ..基本上所有不包含字符。 2)我想在寫入控制檯之前刪除字符串中的所有特殊字符。 「神應印神 & QUOT;包括應印:quoteIncluding 「發現應該發現

+1

我聞到[正則表達式](http://download.oracle.com/javase/tutorial/essential/regex/)。 – JMelnik 2011-05-12 05:45:47

+0

「..一切都不包含字符..」這是線索!爲什麼不考慮'刪除',爲什麼不考慮'包括','A-Z'和'a-z'只有26 + 26個字母。 – 2011-05-12 05:52:20

+0

你到目前爲止嘗試過什麼? – MatthewD 2011-05-12 06:21:25

回答

0

當你說‘的人物,’​​我假設你的意思是隻‘A到Z’和「A從A到Z」你可能想使用正則表達式(正則表達式)爲D1E在評論中提到下面是一個使用的replaceAll方法的例子

import java.util.ArrayList; 

public class Test { 
    public static void main(String[] args) { 
     ArrayList<String> list = new ArrayList<String>(5); 
     list.add("\"God"); 
     list.add("&quot;Including"); 
     list.add("'find"); 
     list.add("24No3Numbers97"); 
     list.add("w0or5*d;"); 

     for (String s : list) { 
      s = s.replaceAll("[^a-zA-Z]",""); //use whatever regex you wish 
      System.out.println(s); 
     } 
    } 
} 

這段代碼的輸出如下:。


quotIncluding
找到
NoNumbers

的的replaceAll方法使用正則表達式和替換所有與第二個參數匹配(在這種情況下,空字符串)。

1

Java擁有非常好的Pattern class,它使用正則表達式。你一定要詳細閱讀。一個很好的參考指南是here.

我打算爲您發佈一個編碼解決方案,但styfle擊敗了我!我會做不同,這裏唯一的辦法就是內部的for循環中,我會使用的模式和匹配器類,因爲這樣:

for(int i = 0; i < myArray.size(); i++){ 
    Pattern p = Pattern.compile("[a-z][A-Z]"); 
    Matcher m = p.matcher(myArray.get(i)); 
    boolean match = m.matches(); 
    //more code to get the string you want 
} 

但是過於笨重。 styfle的解決方案簡潔而簡單。

+0

很棒的回答。歡迎來到堆棧溢出! – 2011-05-12 12:44:23

+0

非常感謝!這個社區真棒。 :) – SpacePyro 2011-05-12 13:45:50