[英]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.