带有数字的java字符串

时间:2011-05-12 05:33:02

标签: java

我在Arraylist中有一组字符串。

我想删除只有数字的所有字符串 还有这样的字符串:(0.75%),1.5美元..基本上所有不包含字符的东西。 2)我想在写入控制台之前删除字符串中的所有特殊字符。 “上帝应该印上帝。 & quot;包括应该打印:quoteIncluding '找到应该找到

2 个答案:

答案 0 :(得分:1)

Java拥有一个非常好的Pattern class,它使用了正则表达式。你一定要仔细阅读。一个很好的参考指南是here.

我打算为你发布一个编码解决方案,但是styfle打败了我!我在这里唯一要做的就是在for循环中,我会使用Pattern和Matcher类,如下:

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的解决方案简洁明了。

答案 1 :(得分:0)

当你说“人物”时,我假设你只是指“a到z”和“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方法使用正则表达式模式,并将所有匹配项替换为第二个参数(在本例中为空字符串)。