简体   繁体   English

模式仅通过短字符串找不到行

[英]Pattern doesnt find the line by only a short String

I have a file in the following pattern: 我有以下格式的文件:

100:5,3 100:5,3

50:10,3 50:10,3

2:20,15 2:20,15

with NO free line inbetween (just to kill some misunderstandings) 中间没有空线(只是为了消除误解)

I want to find a line that starts with a Input (lets say 50) , and i dont know the other two values yet. 我想找到以Input(让我说50)开头的行,而我还不知道其他两个值。 IF i find a line that starts with 50, i want to get the other two values and change them according to other stuff. 如果我找到以50开头的行,我想获取其他两个值并根据其他内容进行更改。 lets say i want to rewrite that line into 50:11,4. 可以说我想将该行改写为50:11,4。 IF i dont find a line starting with a input (lets say 40) i want to create a new line that looks like this : 40:1,0. 如果我找不到以输入开头的行(假设输入40),则我想创建一个新行,如下所示:40:1,0。

sofar i dug through Patterns, and my current state is this: 我通过Patterns进行研究,而我目前的状态是:

        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  }

EDIT: 编辑:

And how do i link the Matcher to a File? 以及如何将Matcher链接到文件?

For ease I used in my code FileUtils from Apache commons that you can get with 为了简便起见,我在Apache Commons的代码FileUtils中使用了

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

You can now use a method like this 您现在可以使用这样的方法

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);
}

by simply doing 通过简单地做

processFile(file, 50, 1, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM