2011-05-25 69 views
1

如何从文本文件中删除具有前面符号的文字?检测到符号后删除文字

例如:

This is important information... //but this is a comment 
This is more important info... //and this is another comment 

如何删除的话用符号一起“//但是这是一条评论”?

这里是我的伪代码:

1. If "//" is detected, line.replace "//" symbol 
2. Clear the words after the symbol 
3. Go on to the next line till you see "//" symbol 
4. Repeat steps 1-3 (loop). 

注意:当文件被读出这是发生:

String line; 
while ((line = textReader.readLine()) != null) 
+0

这是一些艰难的正则表达式工作。 – Sid 2011-05-25 22:16:57

回答

1

我假设给定:

This is important information... //but this is a comment 
This is more important info... //and this is another comment 

你想:

This is important information... 
This is more important info... 

像这样的东西应该工作:

Pattern pattern = Pattern.compile("//.*$", Pattern.DOTALL); 
Matcher matcher = pattern.matcher(line); 

line = matcher.replaceFirst(""); 

Pattern就是Java使用正则表达式。这里是关于Java中Java正则表达式的some information。我使用的正则表达式查找两个正斜杠,之后的所有内容直到行尾。然后,匹配的文本被替换为空字符串。 Pattern.DOTALL告诉Java将^$作为开始和结束标记。

编辑

下面这段代码演示了它是如何工作的:

import java.util.regex.*; 

public class RemoveComments { 

    public static void main(String[] args){ 

     String[] lines = {"This is important information... //but this is a comment", "This is more important info... //and this is another comment"}; 
     Pattern pattern = Pattern.compile("//.*$", Pattern.DOTALL); 

     for(String line : lines) { 
      Matcher matcher = pattern.matcher(line); 

      System.out.println("Original: " + line); 
      line = matcher.replaceFirst(""); 

      System.out.println("New: " + line); 
     } 
    } 
} 
+0

什么是模式? – rudna1010 2011-05-25 22:24:52

+1

'Pattern'是你在Java中用来处理正则表达式的东西。 – 2011-05-25 22:26:13

+0

好的,我明白了。我必须导入这些类。 – rudna1010 2011-05-25 22:27:00

0

只是抛出一个想法,你可以玩的字符串

的功能首先定位删除构成特征

int i = indexOf('//', 0); 

然后寻找下一个空间的指数

secondIndex = indexOf(' ',i); 

,那么你可以提取两侧

String s1 = subString(0,i); 

String s2 = subString(secondIndex,i); 

String res = s1+s2; 

这不是最佳的,但应该把工作做好^^

+0

阅读Vivin的答案,使用正如他向你展示的正则表达式可能会更简单(在正则表达式上不太强大:P) – 2011-05-25 22:30:23