[英]Match string after newline
在Java中,我有以下字符串:
uk\learningAid\UserInputs\UserClass.java:16: error: cannot find symbol
player.mvRight(3);
我目前正在使用此正則表達式來匹配16
並且cannot find symbol
:
Pattern pattern = Pattern.compile(":(\\d+):\\serror:\\s(.*)");
但是,我也要匹配player.mvRight(3);
在新的一行。 我該怎么做呢?
我嘗試在reex的末尾添加此\\\\n(.*)
,但未匹配任何內容。
匹配包括新行在內的第一個“;”。
Pattern pattern = Pattern.compile(":(\\d)+:\\serror:\\s(.*)\\n(.*);");
根據您的評論,如果不一定需要使用正則表達式,則可以使用諸如substring()
和indexof()
類的String
方法來獲取某些字符的位置,並將其用作具有特定模式的任何字符串的標記。 下面的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));
}
}
輸出:
16 cannot find symbol
player.mvRight(3);
另外,如果要刪除換行符,可以只調用toProcess = toProcess.replaceAll("\\n", "");
在開始時刪除換行符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.