我想将此示例文件中的某个字符串替换为空值(空字符串)。我用了#34; \"逃避任何会使我的代码工作的东西。我只是想取代"终端:" UNKNOWN" "在此示例文件
中找到示例文件:
SESSIONID: "19670" ENTRYID: "1" STATEMENT: "1" USERID: "%USERNAME%" USERHOST: "%SRCHOSTNAME%" ACTION: "100" RETURNCODE: "0"
SESSIONID: "19670" ENTRYID: "435" STATEMENT: "20" USERID: "%USERNAME%" USERHOST: "%SRCHOSTNAME%" TERMINAL: "UNKNOWN" ACTION: "3" RETURNCODE: "0"
SESSIONID: "19670" ENTRYID: "1" STATEMENT: "1" USERID: "%USERNAME%" USERHOST: "%SRCHOSTNAME%" ACTION: "101" RETURNCODE: "0
预期产出:
SESSIONID: "19670" ENTRYID: "1" STATEMENT: "1" USERID: "%USERNAME%" USERHOST: "%SRCHOSTNAME%" ACTION: "100" RETURNCODE: "0"
SESSIONID: "19670" ENTRYID: "435" STATEMENT: "20" USERID: "%USERNAME%" USERHOST: "%SRCHOSTNAME%" ACTION: "3" RETURNCODE: "0"
SESSIONID: "19670" ENTRYID: "1" STATEMENT: "1" USERID: "%USERNAME%" USERHOST: "%SRCHOSTNAME%" ACTION: "101" RETURNCODE: "0
我的代码:
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("oracle.log"));
ArrayList<String> list = new ArrayList<String>();
while (scan.hasNext()) {
list.add(scan.next());
}
scan.close();
try {
//initiates a new File type file
File file = new File("oracle.log");
//initiates a new buffereed reader "reader"
BufferedReader reader = new BufferedReader(new FileReader(file));
//initialize 2 strings for comparison
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
oldtext = oldtext.replaceAll("%TERMINAL: \"UNKNOWN\"", "");
FileWriter writer = new FileWriter("new_oracle.log");
// the entire file is contained within the String 'oldtext'
writer.write(oldtext);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
输出: 相同的示例文件没有任何更改
答案 0 :(得分:1)
(根据我的评论)
正则表达式中的%
字符与文字&#39;%&#39;匹配。符号。我不确定你在那里尝试做什么,但请尝试删除它。
我知道在某些情况下%
用于匹配任何内容,在这种情况下,您可以在正则表达式中使用.*
,但这会删除行中的所有内容,直到匹配结束。
TERMINAL: \"UNKNOWN\"
我在regex101上测试了它并且工作正常(此工具不需要转义引号,但它们适用于java)https://regex101.com/r/eB2yW9/1
答案 1 :(得分:1)
regexp中有一个不必要的符号。只需改变你的
oldtext = oldtext.replaceAll("%TERMINAL: \"UNKNOWN\"", "");
到
oldtext = oldtext.replaceAll("\\s*TERMINAL: \"UNKNOWN\"","");
使用附加的\ s *,删除TERMINAL之前的所有空格:&#34; UNKNOWN&#34;