简体   繁体   中英

regex complicated scenario during the text of markdown

Given a Markdown source text:

- sometext

- sometext
followingText



- sometext

- sometext
- sometext

I want to replace double newlines \\n\\n to \\nWhiteSpace\\n among the List range;

so with $1 technique of JS , I did

(- [\\s\\S]+?)(?:\\n\\n(?=\\n))|(- [\\s\\S]+?)(?:\\n\\n(?=- )) http://regex101.com/r/hO7vT9

The blue selection is the target where almost working, except the very first double newlines are failed to be selected.

This is because (- [\\s\\S]+?)(?:\\n\\n(?=\\n)) matches first and the (- [\\s\\S]+?)(?:\\n\\n(?=- )) is not evaluated.

Sure, I can revert the order (- [\\s\\S]+?)(?:\\n\\n(?=- ))|(- [\\s\\S]+?)(?:\\n\\n(?=\\n)) , then now

http://regex101.com/r/tR8sN4

Now, the first selection works, but the second selection failes.(compare to the first version, the intended result for the second selection).

Is there any work-around for this?

Of course, you may suggest separate the regex, and replace twice; well I did, and the result is messy, so I would like achieve this in a single regex. The language is JS.

Posting my comment as an answer.

Try the below. Sorry, if this is still not what you want.

regex = new RegExp(/(- [\s\S]+?)(?:(\n){2,}(?=\n|-))/g);
inputString = '- sometext\n\n- sometext\nfollowingText\n\n\n\n- sometext\n\n- sometext\n- sometext';
outputString = inputString.replace(regex,'$1\nWhiteSpace\n');
console.log(outputString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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