Pattern只能通过一个短字符串找到该行

时间:2015-04-02 11:43:05

标签: java android regex

我有一个以下模式的文件:

100:5,3

50:10,3

2:20,15

中间没有自由线(只是为了消除一些误解)

我想找到一个以Input开头的行(比方说50),我还不知道其他两个值。如果我找到一条以50开头的行,我想获得另外两个值并根据其他内容更改它们。假设我想将该行重写为50:11,4。如果我没有找到以输入开头的行(比方说40)我想创建一个如下所示的新行:40:1,0。

我通过模式挖掘,我目前的状态是:

        Pattern p = Pattern.compile("(d\\+):(\\d+),(\\d+)");
        String inputString = Integer.toString(""+someValue+":(\\d+),(\\d+)";
        Matcher m = p.matcher(inputString);
        m.find();

        if (m.matches){  and so on  }

修改

如何将Matcher链接到文件?

1 个答案:

答案 0 :(得分:0)

为了方便起见,我在我的代码中使用了来自Apache commons的FileUtils,你可以使用

compile 'org.apache.commons:commons-io:1.3.2

您现在可以使用这样的方法

private void processFile(File file, int index, int x, int y) throws Exception{
    // load the file lines in an array
    ArrayList<String> lines = (ArrayList<String>)FileUtils.readLines(file);

    if(lines == null)
        return;

    // create the patter to match the required row
    Pattern p = Pattern.compile(index + ":(\\d+),(\\d+)");
    boolean found = false;
    // loop the lines to find the one we want
    for(int i = 0; i < lines.size(); i++){
        Matcher m = p.matcher(lines.get(i));
        m.find();
        if(m.matches()){
            // when we find it we change it to what we need
            lines.set(i, index + ":" + x + "," + y);
            // we mark that we found it and don't need to add it at the end
            found = true;
            break;
        }
    }
    // if we still haven't found it add the line at the end of the array
    if(!found)
        lines.add(index + ":" + x + "," + y);

    // write the array to a file
    FileUtils.writeLines(file, lines);
}

简单地做

processFile(file, 50, 1, 1);