【问题标题】:Java Pattern match from text file来自文本文件的 Java 模式匹配
【发布时间】:2017-01-08 13:49:55
【问题描述】:

我有一个文件,我将它转换成一个字符串,它有几行。我正在尝试更改目录的位置,即该行

Dir=C:\\Users\\admin\\AppData\\Local\Temp

此路径可能因文件而异且长度未知。 永远都是

Dir="something"\Temp.

我是新手,感谢您的帮助。我假设它是字符的转义..但我不确定,我考虑过使用正则表达式,但我认为我会遇到同样的问题。

预期

Dir=C:\\Users\\admin\\AppData\\Local\\Temp

C:\\Users\\admin\\AppData\\Local\\

目录=\\\\LocalPC\\LocalTemp

实际

Dir=C:\\Users\\admin\\AppData\\Local\\Temp

C:\\Users\\admin\\AppData\\Local\\

Dir=C:\\Users\\admin\\AppData\\Local\\Temp

public class test
{
    public String fileText;

    public static void main(String[] args)
    {
     StartUpFile bob = new StartUpFile();

       System.out.println(bob.showFile());
       System.out.println(bob.temp());

       bob.change();
       System.out.println(bob.showFile());

    }
}

public class StartUpFile
{
    private String fileText;
    private String newText;
    /**
     * Constructor for objects of class StartUpFile
     */
    public StartUpFile()
    {
         newText = "\\\\"+"LocalPC";
         fileText = "Dir=C:"+"\\\\"+"Users"+"\\\\"+"admin"+"\\\\"+"AppData"+"\\\\"+"Local"+"\\\\"+"Temp";
    }
    /**
    * I want to ID the text bewtween "Dir=" and "Temp"
    */
    public String temp()
    {
      int startTemp = fileText.indexOf("Dir=") + 4;
      int EndTemp = fileText.indexOf("Temp");
      return fileText.substring(startTemp,EndTemp);
    }
    /**
    * show the string
    */ 
    public String showFile()
    {
        return fileText;
    }
    /**
     * swap the temp string for the newText
     */
    public void change()
    {
        fileText = fileText.replaceAll(temp(),newText);
    }
}

【问题讨论】:

  • 我最终使用了类似的东西

标签: java string text replace


【解决方案1】:

有人同意使用正则表达式,所以我把它搞砸了 它们看起来像是我应该擅长的东西。

我最终得到了

String result = fileText.replaceAll("^*(?<==).*$", newText);

我读为从一行开始之后的任何内容 = 匹配任何符合我目的的行尾的内容。 但是,如果有人知道如何在“temp”之前陈述任何内容,我认为它会更干净。谢谢你。我认为是“年轻的米莉”发了帖子,然后又删除了他的\她的帖子

或者它是“112g”我不确定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2014-09-18
    • 2023-03-23
    相关资源
    最近更新 更多