gpt4 book ai didi

java - 如何使用 ReplaceAll() 方法将整个字符串替换为空值?

转载 作者:行者123 更新时间:2023-12-02 04:23:29 25 4
gpt4 key购买 nike

我想将此示例文件中的某个字符串替换为空值(空字符串)。我使用“\”来转义任何能让我的代码工作的东西。我只想替换此示例文件中的“TERMINAL: "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();
}

}

输出:相同的示例文件,没有任何更改

最佳答案

(基于我的评论)正则表达式中的 % 字符与文字“%”符号匹配。我不确定您想在那里做什么,但请尝试将其删除。

我知道在某些情况下 % 用于匹配任何内容,在这种情况下您可以在正则表达式中使用 .*,但这会删除队列中的所有内容直到比赛结束。

终端:\“未知\”

我在 regex101 上测试了它,它工作正常(该工具不需要转义引号,但对于 java 则需要转义)https://regex101.com/r/eB2yW9/1

关于java - 如何使用 ReplaceAll() 方法将整个字符串替换为空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32474872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com