简体   繁体   English

如何检测括号(在行尾或新行)?

[英]How to detect bracet (at the end of line or new line)?

This is my code.这是我的代码。

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 I have text file如果我有文本文件

if (...) {
}

and 

if (...)
{
}

output is:输出是:

  • bracet end of line are: 1大括号行尾是:1
  • bracet new line are: 1大括号新行是:1

Thank you for answering.谢谢你的回答。

You read the file line by line.您逐行读取文件。 Hence, there is no chance to find the character \\n followed by another character in the same String.因此,没有机会在同一字符串中找到字符\\n后跟另一个字符。 Hence, '\\n' + "{" will never be found.因此,永远不会找到'\\n' + "{"

You can do it with simple regex :你可以用简单的正则表达式来做到:

for(String line : Files.readAllLines(Paths.get("/path/to/input.txt"))) {
  if(line.matches("\\{.*")) {
    bracketNewLine++;
  }

  if(line.matches(".* \\{")) {
    bracketWithSpace++;
  }
}

You could use some regex like this:你可以像这样使用一些正则表达式:

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
    }
}

When you use nextLine() method, you already have the source line by line.当您使用nextLine()方法时,您已经拥有一行一行的源代码。 The only thing you should do is checking those lines in every loop with existing String methods : startsWith() , endsWith() .您唯一应该做的就是使用现有的 String 方法检查每个循环中的这些行: startsWith()endsWith() If we assume that you are correctly obtaining line string in each loop, inside of that while block should be like that:如果我们假设您在每个循环中都正确获取了行字符串,则该 while 块的内部应该是这样的:

if(line.startsWith("{"))
    bracketNewLine++;
if(line.endsWith("{"))
    bracketWithSpace++;

PS1 hasNext() method does not assure us that we have one more new line. PS1 hasNext()方法并不能保证我们还有一个新行。

PS2 searching a string with fixed size space is not a true approach. PS2 搜索具有固定大小空间的字符串不是真正的方法。 You may use regex instead of that : ^[\\s]*{您可以使用正则表达式代替: ^[\\s]*{

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM