【问题标题】:Regex to remove blank lines, unless multi-line is present正则表达式删除空行,除非存在多行
【发布时间】:2018-01-31 21:58:38
【问题描述】:

我正在寻求帮助,以允许我的用户缩小某些文本输出的格式,以满足他们的偏好。

例子:

User list Summary:


Title:
- Big Pink

Student:
- Philip J Fry

Grade:
- A

Issues:
- This issue
- That issue

Improvements:
- This thing
- That thing
- The other thing

我希望能够将单个答案缩短为一行,但不考虑多行答案。这样上面就变成了:

User list Summary:

Title: Big Pink
Student: Philip J Fry
Grade: A
Issues:
- This issue
- That issue
Improvements:
- This thing
- That thing
- The other thing

我已经走到这一步了:https://jsfiddle.net/hematogones/0d4g0akh/

感谢您的帮助!

【问题讨论】:

  • 您熟悉 regex101.com 的强大实用程序吗?
  • 所以 Improvements: this thing 只有 1 个 -this thing ?
  • @Pytth 谢谢 - 我不知道那个网站。我一直在尝试,它确实是学习正则表达式的好资源。我一直在使用 Regexr,但是 Regex101 有更详细的解释。

标签: javascript regex match


【解决方案1】:

您可以使用它,使用否定前瞻来确保仅在没有其他人跟随时折叠冒号后的连字符:

text.replace(/:\r?\n-\h*(.*)$(?!\r?\n-)/gm, ": $1" ).replace(/^\s*\r?\n/gm,'');

const text = $("#outPut").val();
$(".switch").on("click", function(){	
    var text_new = "";
    if (this.id == "switchto"){
        text_new = text.replace(/:\r?\n-\h*(.*)$(?!\r?\n-)/gm, ": $1" ).replace(/^\s*\r?\n/gm,'');
        $("#outPut").val(text_new);
    }
    if (this.id == "switchback"){
        $("#outPut").val(text);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="outPut" style="width:60%; min-height:180px">
User list Summary:


Title:
- Big Pink

Student:
- Philip J Fry

Grade:
- A

Issues:
- This issue
- That issue

Improvements:
- This thing
- That thing
- The other thing

+ Final score:
- 78%

</textarea>
<br>
<input type="button" class="switch" id="switchto" value="Switch synoptic">
<input type="button" class="switch" id="switchback" value="Switch back">

【讨论】:

  • 我很震惊 JS 知道水平空格 \h
  • 太棒了,我也不知道!
  • $1 在替换语法中有什么作用?
  • $1 重复括号中匹配的内容:不应删除该部分。
猜你喜欢
  • 2021-04-10
  • 1970-01-01
  • 2015-12-17
  • 2011-01-28
  • 2016-06-17
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多