在检测到符号后删除单词

| 如何从文本文件中删除带有符号的单词? 例如:
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) 
    
已邀请:
我假设给出:
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正则表达式的一些信息。我使用过的正则表达式会查找两个正斜杠,然后查找所有正斜杠,直到行尾为止。然后,将匹配的文本替换为空字符串。
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); 
      } 
   } 
}
    
只要提出一个想法,就可以使用String的功能 首先找到要删除的字符
int i = indexOf(\'//\', 0);
然后寻找下一个空格的索引
secondIndex = indexOf(\' \',i);
然后你可以提取双方
String s1 = subString(0,i);

String s2 = subString(secondIndex,i);

String res = s1+s2;
这不是最佳选择,但应该完成工作^^     
您可以使用
String.replaceAll()
在一行中进行正则表达式替换:
line = line.replaceAll(\"//.*$\", \"\");
    

要回复问题请先登录注册