正則表達式
回答
參見前面的:Java - regular expression finding comments in code,或者通過相關查詢從谷歌某些隨機鏈接:http://ostermiller.org/findcomment.html
試試這個:
public class Test {
// comment 1
/*
comment 2
// no line comment
*/
char c = '"'; // comment 3, " is not the start of a string literal!
String s = "/* no comment */ ... /*";
String t = "*/ also // not a comment";
private static String getContentsOf(String fileName) throws FileNotFoundException {
Scanner scan = new Scanner(new File(fileName));
StringBuilder b = new StringBuilder();
while(scan.hasNextLine()) {
b.append(scan.nextLine()).append("\n");
}
return b.toString();
}
public static void main(String[] args) throws FileNotFoundException {
String anyChar = "[\\s\\S]";
String singleLineComment = "//[^\r\n]*";
String multiLineComment = "/\\*" + anyChar + "*?\\*/";
String stringLiteral = "\"(?:\\\\.|[^\"\r\n\\\\])*\"";
String charLiteral = "'(?:\\\\.|[^'\r\n\\\\])+'";
String regex = String.format("(%s)|(%s)|(%s)|(%s)|(%s)",
singleLineComment, // group 1
multiLineComment, // group 2
stringLiteral, // group 3
charLiteral, // group 4
anyChar); // group 5
Matcher m = Pattern.compile(regex).matcher(getContentsOf("Test.java"));
while(m.find()) {
String matched = m.group();
if(m.group(1) != null || m.group(2) != null) {
System.out.println("matched = " + matched);
}
}
}
}
它打印:
matched = // comment 1
matched = /*
comment 2
// no line comment
*/
matched = // group 1
matched = // group 2
matched = // group 3
matched = // group 4
matched = // group 5
或者,也許更健壯的解決方案是使用一個小解析器或解析器生成器。 ANTLR有一個很好的選擇,只定義一部分語言的語法,而忽略其餘部分。我在this previous Q&A中證明了這一點。缺點是你需要學習一些ANTLR ...
不錯的一個!但是'\ u002F * * /'呢? :P – 2011-03-09 10:18:26
@Alan:糟糕的運動! :)我會把它作爲讀者的練習。 – 2011-03-09 10:23:41
雖然它可以用正則表達式解決,但解析任何類型的結構化標記時,最好的解決方案是使用實際理解所用語言的解析器。
在這種情況下:使用Java grammar的Java源解析器,如javaparser或ANTLR的定製解決方案。
- 1. 正則表達式(正則表達式)
- 2. 正則表達式(正則表達式)
- 3. 正則表達式正則表達式正則表達式使用正則表達式,但不是與Python
- 4. PHP-MySQLi替換爲正則表達式/正則表達式/正則表達式
- 5. 正則表達式正則表達式返回的值正則表達式
- 6. 正則表達式正則表達式模仿正則表達式
- 7. 正則表達式表達
- 8. 正則表達式表達
- 9. Python的正則表達式:「喜歡」正則表達式模式?
- 10. 正則表達式
- 11. 正則表達式
- 12. 正則表達式?
- 13. 正則表達式
- 14. 正則表達式
- 15. 正則表達式。
- 16. 正則表達式
- 17. 正則表達式
- 18. 正則表達式@#$ +:=&* _-
- 19. 正則表達式
- 20. 正則表達式
- 21. 正則表達式
- 22. 正則表達式
- 23. 正則表達式
- 24. 正則表達式
- 25. 正則表達式
- 26. 正則表達式
- 27. 正則表達式
- 28. 正則表達式
- 29. 正則表達式
- 30. 正則表達式
如果你輸入一個實際的標題,系統會爲你做一個搜索,所以你不會發布不必要的重複。 – 2011-03-09 14:12:21