简体   繁体   English

用Javascript Regex替换不包含特定字符串的行的回车

[英]Replace carriage return for lines not containing specific string by Javascript Regex

I have some text line following 我下面有一些文字行

Procedure Gato
Do task1
    If early Then come back
    turn 2
End Procedure
Schedule Balo
    If late Then go to home
    turn 2
End Schedule'

The result I need is 我需要的结果是

Procedure Gato: Do task1: If early Then come back
    turn 2: End Procedure
Schedule Balo: If late Then go to home
    turn 2: End Schedule'

I used pattern \\(?!\\n.*(\\b(Procedure |Schedule |Then )).*)\\n\\ to replace all carriage return not containing "Procedure" or "Schedule" or "Then" before. 我使用模式\\(?!\\n.*(\\b(Procedure |Schedule |Then )).*)\\n\\替换了以前所有不包含“ Procedure”或“ Schedule”或“ Then”的回车符。 However it works well for only "Procedure" and "Schedule" not including "Then". 但是,它仅对“过程”和“计划”(不包括“然后”)有效。 How to get the exact result as I need? 如何获得我需要的确切结果? Glad to receive some advice. 很高兴收到一些建议。

This pattern will do the job: 此模式将完成此工作:

(^(?:(?!Then)(?! Procedure)(?! Schedule).)*)(\n\s*)

Its basically capturing the lines that don't have the words on the lookAheads and replacing \\n\\s* with the space( \\s* mostly for next line tabs). 它基本上是捕获在lookAheads上没有单词的行,并用空格代替\\n\\s*\\s*主要用于下一行选项卡)。 I captured the group with the rest of the line also so the replacement must be $1: 我还捕获了该行的其余部分,因此替换必须为$1:

See Demo 观看演示

Change: 更改:

|Then

to: 至:

|.*Then

or replace the .* with a more restrictive regex. 或使用限制性更强的正则表达式替换.* For example: 例如:

/(?!\n.*(\b(Procedure |Schedule |.*?Then )).*)\n/g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM