【问题标题】:How do I surround my line of text with tags?如何用标签包围我的文本行?
【发布时间】:2018-03-06 23:38:16
【问题描述】:

我正在使用 Visual Studio 2017,尝试使用正则表达式进行搜索和替换以执行以下操作。我想用<li>line</li>包围我的文本文件中的每一行

例如:

This is line 1 to be surrounded with list item tags
This is line 2 to be surrounded with list item tags
This is line 3 to be surrounded with list item tags

想要的输出

<li>This is line 1 to be surrounded with list item tags</li>
<li>This is line 2 to be surrounded with list item tags</li>
<li>This is line 3 to be surrounded with list item tags</li>

我尝试了以下方法:

搜索:^.*$
替换:&lt;li&gt;$1&lt;/li&gt; 结果是:

<li>$1</li>
<li>$1</li>
<li>$1</li>

我该怎么做?

【问题讨论】:

  • 到目前为止你得到了什么?
  • $1 应该引用的正则表达式中的捕获组在哪里?

标签: c# regex visual-studio


【解决方案1】:

尝试在您用于搜索的正则表达式周围添加括号

搜索:(^.*$)
替换&lt;li&gt;$1&lt;/li&gt;

如果您想进行第二次替换,则需要在“搜索”正则表达式周围加上另一组括号

【讨论】:

  • 捕获组中包含换行符\r。
  • 您指出搜索的正则表达式不正确是对的,但在他的情况下,他似乎被困在文字 $1 的打印上
  • 这是我需要的。但我想知道如何不包括 \r?
  • @Rod,试试^(.*)\r?$。请注意, \r 现在位于捕获组之外。 (也可以在这里查看更多信息:docs.microsoft.com/en-us/visualstudio/ide/…,尤其是关于端线锚)
【解决方案2】:

搜索:^([^\r\n]+?)(\r?\n?)$

替换为:&lt;li&gt;$1&lt;/li&gt;$2

【讨论】:

  • 这将要求您在文件的最后一行有一个新行
  • 这只是……很奇怪。
猜你喜欢
  • 2012-12-25
  • 2012-03-16
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 2011-08-23
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多