[英]Replace a block of text using a pattern of Regex (in java)
我正在嘗試使用正則表達式從文件中刪除一個文本塊。 現在我將文件的內容放在一個String
但Matcher
找不到該模式。 示例文件是:
\begin{comment}
this block should be removed
i.e. it need to be replaced
\end{comment}
this block should remains.
\begin{comment}
this should be removed too.
\end{comment}
我需要找到以\\begin{comment}
並以\\end{comment}
結尾的塊,然后刪除它們。 這是我使用的最小代碼。 我正在使用的正則表達式是\\\\begin\\{.*?\\\\end\\{comment\\}
,應該找到並以'\\ begin'開頭的模式,直到第一次出現'\\ end {comment}'。 我在Notepad ++工作。
但是使用這個java代碼,它會找到第一個'\\ begin'和最后'\\ end'行並刪除它們之間的所有內容。 我想保留不在塊內的線。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class main {
public static void main(String[] args) {
String output;
String s = "\\begin{comment}\n"+
"this block should be removed\n"+
"i.e. it need to be replaced\n"+
"\\end{comment}\n"+
"this block should remains.\n"+
"\\begin{comment}\n"+
"this should be removed too.\n"+
"\\end{comment}";
Matcher m = Pattern.compile("\\\\begin\\{comment(?s).*\\\\end\\{comm.*?\\}").matcher(s);
while(m.find())
{
System.out.println(m.group(0));
output = m.replaceAll("");
}
m = Pattern.compile("\\begin").matcher(s);
while(m.find())
{
System.out.println(m.group(0));
output = m.replaceAll("");
}
}
}
更新:
我用這個在線工具找到它。 Matcher m = Pattern.compile(“\\\\ begin \\ {comment(?s)。 \\\\ end \\ {comm。?\\}”)。matcher(s );
你必須在2點修復你的代碼:
該模式應該與您的Notepad ++等效,該星應該跟?
懶惰 :
Matcher m = Pattern.compile("\\\\\\\\begin\\\\{comment}(?s).*?\\\\\\\\end\\\\{comment}").matcher(s); -------------------------------------------------------^
請注意,僅當不存在嵌套注釋部分時,此模式才能正常工作。
后一個修復關系到邏輯:如果你調用匹配器replaceAll函數,它會在執行時替換每個匹配的部分(已經在第一個m.find()
循環執行)。 如果您需要循環來檢查每個注釋塊,請將其替換為:
output = m.replaceFirst("");
或者只是應用output = m.replaceAll("");
沒有任何循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.