如何解决.contains() 在 java 中找不到多行
我正在尝试为文本上的特定行执行 string .contains() 我使用 Files.readAlllines 读取文件的行。 我正在尝试做
Path c1=Paths.get(prop.getProperty("testPWP"));
List<String> newLines1 = new ArrayList<String>();
for (String line : Files.readAllLines(c1,StandardCharsets.UTF_8)) {
if (line.contains("return test ;\r\n" + " }")) {
newLines1.add( line.replace("return test ;\r\n" +
" }","return test ;\r\n" +
" }*/"));
}
else {
newLines1.add(line);
}
}
Files.write(c1,newLines1,StandardCharsets.UTF_8);
我基本上试图在 return 语句之后注释 } 但 contains 函数没有将其识别为文件中的新行。 对这个问题有什么帮助吗?
解决方法
您可以使用replaceable参数来替换正则表达式。
演示:
public class Main {
public static void main(String[] args) {
String find = "return test ;\r\n" + " }";
String str = "Hello return test ;\r\n" + " } Hi Bye";
boolean found = str.contains(find);
System.out.println(found);
if (found) {
str = str.replaceAll("(" + find + ")","/*$1*/");
}
System.out.println(str);
}
}
输出:
true
Hello /*return test ;
}*/ Hi Bye
此处 $1
指定 capturing group、group(1)
。
在您的程序中,str
的值可以填充如下:
String str = Files.readString(path,StandardCharsets.US_ASCII);
如果您的 Java 版本低于 11,请执行以下操作:
String str = new String(Files.readAllBytes(Paths.get(path)),StandardCharsets.US_ASCII);
,
您可能已经注意到,Files.readAllLines
读取所有行并返回一个列表,其中每个字符串代表一行。要完成您要执行的操作,您需要将整个文件读入单个字符串,或者连接已有的字符串,或者更改替换方法。最简单的方法是将文件的全部内容读入一个字符串,具体实现如下:
String content = new String(Files.readAllBytes(Paths.get("path to file")));
或者如果您使用的是 Java 11 或更高版本:
String content = Files.readString(Paths.get("path to file"));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。