由VbCrLf +拆分的正则表达式忽略双引号内的VbCrLf。 VB.NET

时间:2013-08-07 14:46:15

标签: regex vb.net

仍在尝试了解正则表达式。 我需要在VbCrLf上拆分字符串,但不是在双引号内。

所以我的String是使用stringbuilder构建的,如下所示:

“ABCDEF”
“这是 SampleText“

所以我将其转换为IO Stream并解析它。在IO流中,我得到一个单独的字符串来解析 “ABCDEF”vbCrLf“这是vbCrLf SampleText”

现在我将IOStream转换为字符串并希望将其拆分。 所以需要的输出是

“ABCDEF”
“这是SampleText”

(如果可能的话,还可以解释我的表达方式,以便根据我的需要理解和修改)

谢谢

1 个答案:

答案 0 :(得分:0)

描述

我认为简单地使用正则表达式匹配例程然后输出每一行会更容易。这个正则表达式将:

  • 假设\r\n等同于VbCrLf
  • 匹配整行和文字
  • 修剪分隔\r\n以模仿split命令将如何删除分隔符
  • 即使引用的字符串包含\r\n
  • ,也会将引用的字符串保持在一起

^(?:[^"\r\n]|"[^"]*")*(?=\r\n|\Z)

enter image description here

实施例

Live Demo of the Regex

示例文字

line 1
line 2
line 3 "this is 
line 3a
line 3b
line 3c" and some more text
line 4
line 5

<强>代码

VB.NET Code Example:
Imports System.Text.RegularExpressions
Module Module1
  Sub Main()
    Dim sourcestring as String = "replace with your source string"
    Dim re As Regex = New Regex("^(?:[^""\r\n]|""[^""]*"")*(?=\r\n|\Z)",RegexOptions.IgnoreCase OR RegexOptions.IgnorePatternWhitespace OR RegexOptions.Multiline OR RegexOptions.Singleline)
    Dim mc as MatchCollection = re.Matches(sourcestring)
    Dim mIdx as Integer = 0
    For each m as Match in mc
      For groupIdx As Integer = 0 To m.Groups.Count - 1
        Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames(groupIdx), m.Groups(groupIdx).Value)
      Next
      mIdx=mIdx+1
    Next
  End Sub
End Module

找到匹配

[0][0] = line 1
[1][0] = line 2
[2][0] = line 3 "this is 
line 3a
line 3b
line 3c" and some more text
[3][0] = line 4
[4][0] = line 5
相关问题