2013-08-20 104 views
2

我正在从字符串中删除特定的字符串。首先我读的文本文件通过文件阅读器,并在此之后我正在存储文件的内容到字符串数组和字符串数组除去一些特定的字符串如何从java中的字符串中删除特定的字符串

输入文本是:

:VL 
15 
n 
3 c 

09:0.023 
15th:0.023 
1987:0.025 
1st:0.025 
2:0.013 
2.0:0.043 
2003:0.056 
2005:0.056 
    Top Terms: 
    Weight : 
props 
optional 
: Point: 
    1.0: 
15th:0.068 

现在我正在读这个文本和存储到字符串数组是:String [] Result

我的代码:

for(String t1: Result){ 
Pattern = Pattern.compile("\\b:[0-9]\\b"); 
       matcher = pattern.matcher(t1); 
       if(matcher.find()){ 
        System.out.println(t1); 
} 

输出我得到:

09:0.023 
15th:0.023 
1987:0.025 
1st:0.025 
2:0.013 
2.0:0.043 
2003:0.056 
2005:0.056 
    Top Terms: 
    Weight : 
15th:0.068 

我不希望这样的输出。我的输出应该是这样:

09:0.023 
15th:0.023 
1987:0.025 
1st:0.025 
2:0.013 
2.0:0.043 
2003:0.056 
2005:0.056 
15th:0.068 

给我什么正则表达式我要申请得到这个输出一些想法。

+0

我想你需要删除没有任何数字的字符串 –

+0

告诉我正则表达式删除没有任何数字的字符串。 –

+0

我怀疑''2005:0.056 热门词汇: 重量:“'实际上可能是一条线。 –

回答

0

我明白了。

String []result; 
String returnValue: 
        file = new FileReader(filename); 
      reader = new BufferedReader(file); 
      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       returnValue += line + "\n"; 
      } 
      result = returnValue.split("\\s+"); 
    for(String t1: result){ 
    Pattern = Pattern.compile("\\b:[0-9]\\b"); 
        matcher = pattern.matcher(t1); 
        if(matcher.find()){ 
         System.out.println(t1); 
    } 

和它给输出同样是这样的:我找这个我将数据存储到字符串数组,它是String [] Result

适用相同的代码使用正则表达式\\s+文件读取完成后,分割内容:

09:0.023 
15th:0.023 
1987:0.025 
1st:0.025 
2:0.013 
2.0:0.043 
2003:0.056 
2005:0.056 
15th:0.068 
1

我怀疑

2005:0.056 
    Top Terms: 
    Weight : 

实际上是一个单行......不知何故。

该正则表达式应该(只)匹配你有一个单一数字组成的单词的行。


我猜你实际上知道这一点(而你“忘了提及它”)。

如果要匹配这些:

2005:0.056 
15th:0.023 
1st:0.023 
2nd:0.023 
3rd:0.023 

但不是这些:

2005:0.056 Top Terms: Weight : 
1.0: 

那么你需要一个严格的正则表达式,并match()而不是找到;例如

pattern = Pattern.compile(
       "\\s*[0-9]+(st|nd|rd|th|(\\.[0-9]+))?:[0-9]+\\.[0-9]+\\s*"); 
for (String t1: Result) { 
    matcher = pattern.matcher(t1); 
    if (matcher.match()) { 
     System.out.println(t1); 
    } 
} 

但在这一点上,我猜你实际标准为一个“有效”路线是什么。

0

这可能对你有帮助。

BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt")); 
    String str = null; 
    while ((str = br.readLine()) != null) { 
     if((str.contains(":"))){ 
      String[] arr=str.split(":"); 
       if(arr.length==2){      
         if(Pattern.compile("\\d").matcher(arr[1]).find()){ 
          System.out.println(str); 
         }      
       } 
     } 
    } 

出把

09:0.023 
15th:0.023 
1987:0.025 
1st:0.025 
2:0.013 
2.0:0.043 
2003:0.056 
2005:0.056 
15th:0.068 
0
for(String t1: Result){ 
      Pattern p= Pattern.compile("\\b:[0-9]\\b"); 
          Matcher m= p.matcher(t1); 
          if(m.find()){ 
           System.out.println(t1); 
      } 

此代码工作绝对没问题!

+0

它不工作,因为'“2005:0.056顶部条款:重量”'在同一行 –

相关问题