检测到符号后删除单词

时间:2011-05-25 22:14:57

标签: java regex comments

如何从文本文件中删除前面有符号的文字?

例如:

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) 

3 个答案:

答案 0 :(得分: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); 
      } 
   } 
}

答案 1 :(得分:0)

只要抛出一个想法,就可以使用String

的功能

首先找到删除的字符

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

然后查找下一个空格的索引

secondIndex = indexOf(' ',i);

然后你可以提取双方

String s1 = subString(0,i);

String s2 = subString(secondIndex,i);

String res = s1+s2;

这不是最佳,但应该完成工作^^

答案 2 :(得分:0)

您可以使用String.replaceAll()在一行中进行正则表达式替换:

line = line.replaceAll("//.*$", "");