删除不带正则表达式的java代码中的所有注释

删除不带正则表达式的java代码中的所有注释,java,java-8,Java,Java 8,我正在做一个家庭作业,我需要阅读一个java源文件并删除其中的所有注释。其余的样式应该保持不变 我已经用正则表达式完成了任务 但是我希望不使用regex也能做到这一点。 示例输入 // My first single line comment class Student { /* Student class - Describes the properties of the student like id, name */ int studentId; // Unique St

我正在做一个家庭作业,我需要阅读一个java源文件并删除其中的所有注释。其余的样式应该保持不变

我已经用正则表达式完成了任务

但是我希望不使用regex也能做到这一点。

示例输入

// My first single line comment

class Student {

  /* Student class - Describes the properties
  of the student like id, name */

  int studentId; // Unique Student id
  String studentName; // Name of the student
  String junk = "Hello//hello/*hey";

} // End of student class
class Student {

  int studentId;
  String studentName;
  String junk = "Hello//hello/*hey";

}
结果

// My first single line comment

class Student {

  /* Student class - Describes the properties
  of the student like id, name */

  int studentId; // Unique Student id
  String studentName; // Name of the student
  String junk = "Hello//hello/*hey";

} // End of student class
class Student {

  int studentId;
  String studentName;
  String junk = "Hello//hello/*hey";

}
我的想法是读每一行

1) 检查前两个字符

  • 如果以//=>开头,请删除该行

  • 如果以/*=>开头,则删除所有行,直到*/

2) 另一个场景是处理

示例-int studentId;//注释或/*注释*/


有人能提供更好的方法吗?

如果您想尝试除正则表达式之外的其他方法,那么一种可能是使用状态机。至少有五种状态:开始、在普通代码中、在//注释中、在/*…*/评论并停止

在启动状态下启动。每个状态都会处理输入,直到出现某种情况,使其切换到不同的状态。停止状态结束处理,执行任何必要的整理,如关闭文件

请记住,您需要处理格式错误的输入,以及偷偷摸摸的输入:

System.out.println("A Java comment may start with /* and finish with */");

我将留给您来解决如何处理这个问题。

不要检查前两个字符,而是搜索
/
,然后从该点移到新行。除了删除直到
*/
@HypnicJerk感谢您的回复,对于
/*/
的想法与此相同。如果我搜索整行文本,如果我有一个字符串声明,比如-String junk=“Hello//Hello”;这可能会引起问题right@user3451476能否提供一个字符串示例,说明它的外观以及您希望它的外观like@NickDiv我已经更新了这个问题。显然,你的想法行不通,因为你根本没有考虑字符串文字。请记住,在字符串文字中,可以通过反斜杠转义字符。哦,那序列呢?你也应该正确处理这些问题吗?我怀疑你是否真的“通过使用正则表达式完成了任务”。但是,如果您已经了解了基于regex的解决方案,那么手动实现完全相同的逻辑有什么困难呢?