私はコードでいくつかのテキストファイルを持っています。のJava正規表現は、プログラム
/*Comment here*/
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("First");
/*Comment here
*and
*here*/
primaryStage.setScene(new Scene(root, 640, 480));
primaryStage.show();//Comment this
//and comment that
}
そして、それはそのように見えるように:ファイルを読み込み、それをすべて
public void delCommentAction(ActionEvent actionEvent) throws IOException {
String line = null;
FileReader fileReader =
new FileReader(filePath);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
FileWriter fw = new FileWriter(filePathNoComm);
BufferedWriter bw = new BufferedWriter(fw);
while((line = bufferedReader.readLine()) != null) {
bw.write(delComments(line));
}
bw.close();
}
を置き換えるしかし
public String delComments(String content){
Pattern regex = Pattern.compile("/\\*.*?\\*/|/{2,}[^\\n]*", Pattern.MULTILINE);
Matcher matcher = regex.matcher(content);
String clean = content.replaceAll("(?s:/\\*.*?\\*/)|//.*", "");
return clean;
}
方法:
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("First");
primaryStage.setScene(new Scene(root, 640, 480));
primaryStage.show();
}
私はこれを試してみましたそれは動作しません(コメントは削除されませんでした)
I'dが、これは、単一の正規表現のための多くにあると言います。むしろ、プロパーパーサーでコードを解析し、そのコメントを見つけようとするべきです。 – SomeJavaGuy
あなたが試すことができ[ '" //.*[\r\n]*|(\"[^\\\\\"]*(?:\\\\.[^\\\\\"]* )* \ ")|/\\ * [^ *] * \\ * +([^/*] [* ^] * \\ * +)* /?" '](https://regex101.com/r/yU4aU5/1)。 –