[英]How to detect bracet (at the end of line or new line)?
這是我的代碼。
while(in.hasNext()){
String line = in.nextLine();
in.hasNextLine();
if (line.length() >0){
int k = -1;
k = -1;
while(true){
k = line.indexOf('\n' + "{", k+1);
if(k<0)break;
bracketNewLine++;
}
k = -1;
while(true){
k = line.indexOf(" {", k+1);
if(k<0)break;
bracketWithSpace++;
}
}
}
如果我有文本文件
if (...) {
}
and
if (...)
{
}
輸出是:
謝謝你的回答。
您逐行讀取文件。 因此,沒有機會在同一字符串中找到字符\\n
后跟另一個字符。 因此,永遠不會找到'\\n' + "{"
。
你可以用簡單的正則表達式來做到:
for(String line : Files.readAllLines(Paths.get("/path/to/input.txt"))) {
if(line.matches("\\{.*")) {
bracketNewLine++;
}
if(line.matches(".* \\{")) {
bracketWithSpace++;
}
}
你可以像這樣使用一些正則表達式:
String patternInLine = ".+\\{$";
String patternNewLine = "^\\{":
Pattern p1 = new Pattern(patternInLine);
Pattern p2 = new Pattern(patternNewLine);
while(in.hasNext()) {
String line = in.nextLine();
in.hasNextLine();
Matcher m1 = p1.match(line);
Matcher m2 = p2.match(line);
if(m1.match())
{
//inLine++;
}
else if (m2.match())
{
//newLine++;
}
else
{
//other cases
}
}
當您使用nextLine()
方法時,您已經擁有一行一行的源代碼。 您唯一應該做的就是使用現有的 String 方法檢查每個循環中的這些行: startsWith()
、 endsWith()
。 如果我們假設您在每個循環中都正確獲取了行字符串,則該 while 塊的內部應該是這樣的:
if(line.startsWith("{"))
bracketNewLine++;
if(line.endsWith("{"))
bracketWithSpace++;
PS1 hasNext()
方法並不能保證我們還有一個新行。
PS2 搜索具有固定大小空間的字符串不是真正的方法。 您可以使用正則表達式代替: ^[\\s]*{
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.