替换文本文件中的参数

时间:2015-10-30 07:31:04

标签: java

我有很多带有后续结构的文本文件:FileName_Location.txt。 在文本文件中有三个值,我必须替换它们。

<filename="" location="" extension="">

所以它会是<filename="FileName" location="Location" extension="txt">

我通过文件名获取所有这些值。但是文本文件中的值/参数也可能是错误的,所以我必须覆盖它们。

我的问题是我如何准确找到合适的位置来添加或替换值。

1 个答案:

答案 0 :(得分:1)

这是Java代码大量使用正则表达式,它可以在原始问题的单行上运行。它会提取出几个组,然后重建该行,并在此过程中插入所需的值。

String pattern = "^(<filename=)(\".*\")\\s(location=)(\".*\")\\s(extension=)(\".*\">)$";
String input = "<filename=\"\" location=\"\" extension=\"\">";
// you can uncomment this next line to test the case when values be
// already present in the input line
//String input = "<filename=\"stuff\" location=\"stuff\" extension=\"stuff\">";
System.out.println("Input string:");
System.out.println(input);

// you can replace these next 3 variables with whatever values you want
// e.g. you could put this code into a loop
String fileName = "FileName";           // a new filename
String location = "Location";           // a new location
String extension = "txt";               // a new extension
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
if (m.find()) {
    StringBuilder res = new StringBuilder();
    res.append(m.group(1)).append("\"").append(fileName).append("\" ");
    res.append(m.group(3)).append("\"").append(location).append("\" ");
    res.append(m.group(5)).append("\"").append(extension).append("\">");
    System.out.println("Output string:");
    System.out.println(res);
} else {
    System.out.println("NO MATCH");
}

此代码已经在IntelliJ版本11上进行了测试(是的,我太懒了,无法升级),而且工作正常。

<强>输出:

Input string:
<filename="" location="" extension="">
Output string:
<filename="FileName" location="Location" extension="txt">
相关问题