在 p 标签中包装段落/换行 [英] Wrapping paragraphs/new line in p tags

查看:55
本文介绍了在 p 标签中包装段落/换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个文本文件,需要使用正则表达式将每个段落包装在 p 标签中.

即之前:

第1段第 2 段第 3 段

之后

第1段

<p>第2段</p><p>第3段</p>

我从其他问题中尝试了不同的正则表达式,但没有运气.我得到的最接近的是使用 find (.*?(\n)) 并替换为 <p>$1</p> 但输出看起来像这样:

parag1</p><p></p><p>parag2</p><p></p><p>parag3</p><p></p><p>parag4

知道如何解决这个问题吗?谢谢.

解决方案

你可以使用这个正则表达式:

(.+?)(\n|$)+

并将其替换为:

$1

\n\n

你的正则表达式的问题是,它也匹配空行,因为你说:匹配任何字符次或多次,然后是一个新行".>

您还必须计算最后一段,它可能不会以换行符结尾.

I have multiple text file and need to wrap each paragraph in p tags using regex.

i.e. before:

Paragraph 1

Paragraph 2

Paragraph 3

After

<p>Paragraph 1</p>

<p>Paragraph 2</p>

<p>Paragraph 3</p>

I tried different regexs from other questions but with no luck. The closest i got was to use find (.*?(\n)) and replace with <p>$1</p> but the output looks like this:

<p>parag1
</p><p>
</p><p>parag2
</p><p>
</p><p>parag3
</p><p>
</p><p>parag4

Any idea how can i fix this? Thanks.

解决方案

You can use this regex:

(.+?)(\n|$)+

and replace it with:

<p>$1</p>\n\n

The problem with your regex is, that it is matching empty lines as well, because you're saying: "Match any character zero or more times, followed by a new line".

You also have to take in count the last paragraph, that might not end with a line break.

这篇关于在 p 标签中包装段落/换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆