简体   繁体   English

在换行符后匹配字符串

[英]Match string after newline

Within Java I have this string: 在Java中,我有以下字符串:

uk\learningAid\UserInputs\UserClass.java:16: error: cannot find symbol
player.mvRight(3);

I am currently using this regex to match 16 and cannot find symbol : 我目前正在使用此正则表达式来匹配16并且cannot find symbol

Pattern pattern = Pattern.compile(":(\\d+):\\serror:\\s(.*)");

However, I want to also match player.mvRight(3); 但是,我也要匹配player.mvRight(3); which is on a new line. 在新的一行。 How do I do this? 我该怎么做呢?

I tried adding this \\\\n(.*) at the end of the reex, but it failed to match anything. 我尝试在reex的末尾添加此\\\\n(.*) ,但未匹配任何内容。

匹配包括新行在内的第一个“;”。

Pattern pattern = Pattern.compile(":(\\d)+:\\serror:\\s(.*)\\n(.*);");

As per your comments, if it doesn't necessarily need to be regex then the String methods such as substring() and indexof() can be used to get the position of certain characters and use those as markers for any strings with a certain pattern. 根据您的评论,如果不一定需要使用正则表达式,则可以使用诸如substring()indexof()类的String方法来获取某些字符的位置,并将其用作具有特定模式的任何字符串的标记。 The below SSCCE should work for your String and any of a similar format. 下面的SSCCE应该适用于您的String和任何类似格式。

public  class Test {

    public static void main(String[] args) {
        String toProcess = "uk\\learningAid\\UserInputs\\UserClass.java:16: error: cannot find symbol \nplayer.mvRight(3);";
        int firstCol = toProcess.indexOf(":");
        int secondCol = toProcess.indexOf(":", firstCol+1);
        int lastCol = toProcess.lastIndexOf(":");
        System.out.println(toProcess.substring(firstCol+1, secondCol) + toProcess.substring(lastCol+1));
    }
}

Output: 输出:

16 cannot find symbol 
player.mvRight(3);

Also, if you want the line break removed you can just call toProcess = toProcess.replaceAll("\\n", ""); 另外,如果要删除换行符,可以只调用toProcess = toProcess.replaceAll("\\n", ""); at the beginning to remove the line breaks. 在开始时删除换行符。

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

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