[英]what will be the java regex to Split a string based the last occurance of an unescaped @ character
[英]Java regex to check if last line has unescaped %
我需要檢查 Java 最后一行。 我有一個字符串,它將由 TeX 編譯器進一步處理。 在那里,一行中的第一個 % 被視為注釋,編譯器“看不到”該行的所有 rest。
但是第一個 % 有點棘手,因為它可以被\
轉義,所以\%
應該被忽略。
所以基本上我想檢查最后一行是否以評論結尾?
例如
(a) last line % now with comment
(b) last line with escaped \% and not treated
(c) last line withouth any special chars
(d) last line terminates with %
(e) last line terminates with escaped \%
(f) beginning % but even escaped \% is ignored
對於檢查,我需要肯定: a
, d
和f
而其他應該被忽略。
按照要求我到目前為止的方法:
[^\n]*$
測試最后一行。 很好,但現在我什至不知道如何在最后一行匹配%
。 我會期望一個(%)?
僅當%
可用但偶數 (c) 為正時才匹配,因為它匹配最后一行。
任何人都可以幫助如何只過濾我正在尋找的%
嗎?
您可以使用
(?<!\\)(?:\\{2})*%[^\\%\r\n]*(?:\\[\w\W][^\\%\r\n]*)*\z
請參閱正則表達式演示。
細節
(?<!\\)
- 當前位置左側不允許有\
(?:\\{2})*
- 任何零個或多個雙反斜杠(此模式和前面的模式對於避免匹配以 escaping 反斜杠開頭的%
是必要的,您不能只使用(?<!\\)
)%
- 一個%
字符[^\\%\r\n]*
- 除了\
、 %
以及 CR 和 LF 行尾符號之外的零個或多個字符(?:\\[\w\W][^\\%\r\n]*)*
- 零次或多次出現
\\[\w\W]
- 任何轉義字符, \\
匹配\
並且[\w\W]
匹配任何字符(它可以替換為.
如果您在開頭添加(?s)
DOTALL 內聯嵌入標志選項圖案)[^\\%\r\n]*
- 除\
、 %
和 CR 和 LF 行尾符號之外的任何零個或多個字符。在 Java 中,使用如下模式
String text = "(a) last line % now with comment\n(b) last line with escaped \\% and not treated\n(c) last line withouth any special chars\n(d) last line terminates with %\n(e) last line terminates with escaped \\%\n(f) beginning % but even escaped \\% is ignored";
Pattern p = Pattern.compile("(?<!\\\\)(?:\\\\{2})*%[^\\\\%\r\n]*(?:\\\\[\\w\\W][^\\\\%\r\n]*)*\\z");
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println("Match found!");
}
// => Match found!
請參閱Java 演示。
您可以使用消極的后視來實現您想要的。
演示: https://regex101.com/r/oRqrhv/1
模式: (?<!\\)%
更新1:為了確保我們只匹配最后一行,可以使用atomic group
。
模式: (?>[\s\S]*\n).*(?<!\\)%
詳細信息: [\s\S]*\n
將匹配所有字符,直到最后一個\n
。 原子組, (?>..)
將防止引擎回溯。
匹配成功: https://regex101.com/r/oRqrhv/2
匹配失敗: https://regex101.com/r/oRqrhv/4
注意:如果輸入文本末尾有一個空的新行,例如https://regex101.com/r/oRqrhv/3 ,它將不匹配。 如果這需要匹配,那么我們需要使用負前瞻。
模式: (?>[\s\S]*\n(?<.$))?*(?<!\\)%
。 (?<!$)
確保\n
不緊跟字符串結尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.