【问题标题】:Regexp- replace specific line break in String正则表达式 - 替换字符串中的特定换行符
【发布时间】:2021-12-19 03:02:20
【问题描述】:

我正在寻找一个 regexp,它可以从长字符串中找到特定的换行符 \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)(?!.*#).*$,它很接近,但我不知道如何构建正确的表达式,让我只匹配和删除正确的换行符并保留剩余的文本/字符串.

也许有比使用正则表达式更好的方法?

【问题讨论】:

    标签: java regex regexp-replace


    【解决方案1】:

    你可以使用

    text = text.replaceAll("\\R(?!.*#)", "");
    text = text.replaceAll("(?m)\\R(?=[^\n#]+$)", "");
    

    请参阅regex demo / regex demo #2详情

    • (?m) - Pattern.MULTILINE 嵌入标志选项使此模式中的 $ 匹配行尾,而不是整个字符串的结尾
    • \R - 任何换行序列
    • (?!.*#) - 一个负前瞻,它匹配一个不紧跟任何零个或多个字符的位置,而不是尽可能多的换行符,然后是 # 字符
    • (?=[^\n#]+$) - 除了 LF 和 # 之外,需要一个或多个字符(也将 + 替换为 * 以匹配空行)的正向前瞻。

    在线查看Java demo

    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
    

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2018-07-13
      • 2012-04-26
      • 2011-10-05
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多