假设我有一个名为 str
的字符串变量包含以下值:
~Header 1~
*Content 1*
*Content 2*
~Header 2~
*Content 1*
*Content 2*
*Content 3*
~Header 3~
*Content 1*
我想要的是替换特殊字符,即 ~
与 <b>Header</b>
和*
与 <p>Content</p>
所以它会导致:
<b>Header 1</b>
<p>Content 1</p>
<p>Content 2</p>
<b>Header 2</b>
<p>Content 1</p>
<p>Content 2</p>
<p>Content 3</p>
<b>Header 3</b>
<p>Content 1</p>
然后删除 NewLine 并将其替换为 <br/>
并使其仅一行。
到目前为止,我可以删除 NewLine 并将其替换为 <br/>
然后将其写成一行。
预期结果
<b>Header 1</b><br/><p>Content 1</p><br/><p>Content 2</p><br/><br/><b>Header 2</b><br/><p>Content 1</p><br/><p>Content 2</p><br/><p>Content 3</p><br/><br/><b>Header 3</b><br/><p>Content 1</p>
我当前的代码
Dim str As String = TextBox.Text ' The String Value is inputted from TextBox with Multiline property
Dim newStr As String = Regex.Replace(str, vbLf, "<br/>")
newStr = Regex.Replace(str, vbCr, "<br/>")
MessageBox.Show(newStr)
当前结果
~Header 1~<br/>*Content 1*<br/>*Content 2*<br/><br/>~Header 2~<br/>*Content 1*<br/>*Content 2*<br/>*Content 3*<br/><br/>~Header 3~<br/>*Content 1*
有人可以帮我吗?
最佳答案
假设“~”和“*”字符始终出现在行首和行尾,可以使用以下方法
- 使用
String.Split
创建一个数组,其中str
的每一行都有一个元素. - 循环各行并进行替换。
使用
String.Join
用<br>
重建字符串每个项目之间。Dim str As String = "~Header~" & vbCrLf & "*content*" Dim lines() As String = str.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries) For i As Integer = 0 To lines.Length - 1 If lines(i).StartsWith("~") And lines(i).EndsWith("~") Then lines(i) = "<b>" & lines(i).Substring(1, lines(i).Length - 2) & "</b>" End If If lines(i).StartsWith("*") And lines(i).EndsWith("*") Then lines(i) = "<p>" & lines(i).Substring(1, lines(i).Length - 2) & "</p>" End If Next Dim strNew As String = String.Join("<br>", lines)
[编辑回复评论]
如果你想要 <br>
为每个空行添加,那么我们需要更改 StringSplitOptions
至StringSplitOptions.None
。为此,我们需要确切地知道分隔行的字符(vbCR、vbLf、vbCrLf),如果行由 vbCrLf 分隔,则以下代码应该有效。
Dim str As String = "~Header~" & vbCrLf & "*content*"
Dim lines() As String = str.Split({vbCrLf}, StringSplitOptions.None)
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith("~") And lines(i).EndsWith("~") Then
lines(i) = "<b>" & lines(i).Substring(1, lines(i).Length - 2) & "</b>"
End If
If lines(i).StartsWith("*") And lines(i).EndsWith("*") Then
lines(i) = "<p>" & lines(i).Substring(1, lines(i).Length - 2) & "</p>"
End If
Next
Dim strNew As String = String.Join("<br>", lines)
关于.net - 查找并替换字符串中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35176633/