![](/img/trans.png)
[英]How to skip a specific word when replace the String using regexp in java
[英]Regexp- replace specific line break in String
我正在尋找一個可以從長字符串中找到特定換行符\\n
表達式。
特定的\\n
是不包含特定字符的行之前的那個: '#'
例如:
這是一個很好的#line1\\n這是另一個很好的#line2\\nThis_belongs_to abobe line\\n這仍然可以#line4
代表文本:
this tis a fine #line1
this tis another fine #line2
this_belongs_to abobe line
this tis still is OK #line4
這里的\\n
在 #line2 之后被刪除,導致文本:
this tis a fine #line1
this tis another fine #line2this_belongs_to abobe line
this tis still is OK #line4
我想出了一個正則表達式,如: \\n^(?m)(?!.*#).*$
很接近,但我不知道如何構建正確的,只允許我匹配和刪除正確的換行符並保留剩余的文本/字符串。
也許有比使用正則表達式更好的方法?
您可以使用
text = text.replaceAll("\\R(?!.*#)", "");
text = text.replaceAll("(?m)\\R(?=[^\n#]+$)", "");
請參閱正則表達式演示/正則表達式演示 #2 。 詳情:
(?m)
- Pattern.MULTILINE
嵌入標志選項使$
在此模式中匹配行的結尾,而不是整個字符串的結尾\\R
- 任何換行序列(?!.*#)
- 一個負向前瞻,匹配一個位置后沒有立即跟隨任何零個或多個字符,而不是盡可能多的換行符,然后是#
字符(?=[^\\n#]+$)
- 需要一個或多個字符(也用*
替換+
以匹配空行)而不是 LF 和#
直到行尾的正向前瞻。在線查看Java演示:
String s_lf = "this tis a fine #line1\nthis tis another fine #line2\nthis_belongs_to abobe line\nthis tis still is OK #line4";
String s_crlf = "this tis a fine #line1\r\nthis tis another fine #line2\r\nthis_belongs_to abobe line\r\nthis tis still is OK #line4";
System.out.println(s_lf.replaceAll("\\R(?!.*#)", ""));
System.out.println(s_crlf.replaceAll("\\R(?!.*#)", ""));
System.out.println(s_lf.replaceAll("(?m)\\R(?=[^\n#]+$)", ""));
System.out.println(s_crlf.replaceAll("(?m)\\R(?=[^\n#]+$)", ""));
所有測試用例 - 帶有 CRLF 和 LF 行結尾的字符串 - 導致
this tis a fine #line1
this tis another fine #line2this_belongs_to abobe line
this tis still is OK #line4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.