【问题标题】:Incorrect Regex.Split scan不正确的 Regex.Split 扫描
【发布时间】:2015-08-21 01:07:14
【问题描述】:

这个表达式有问题:;(?!.*(\}|""|')|(\{|""|')),问题是这样的:

这是原始字符串:

abc; def; lalala;
123;
456;
789;
'some string with ; on center';
'an string;
new line;
chars;';
{
this;
doens't;
be;
detected;
};

这就是我想要的:

index      item
---------- --------------------
0          abc
1          def
2          lalala
3          123
4          456
5          789
6          'Some string with ; on center'
7          'an string;
           new line; 
           chars;'
8          {
           this;
           doens't;
           be;
           detected;
           }

但是,这就是返回的内容......

index      item
---------- --------------------
0          abc
1          def
2          lalala
3          123
4          456
5          789
6          'Some string with ; on center'
7          'an string;
8          new line
9          chars;'
           {
10         this;
11         doens't;
12         be;
13         detected;
           }

这个正则表达式我无法获取上述文件的行,并且我在几个在线正则表达式调试器上对其进行了测试,没有得到任何方法。我正在使用 SingleLine 选项,但它们使事情变得更糟。任何的想法?错误在哪里?我可以在哪里升级到我想要的方式?

这是我的代码的一部分(在 VB.NET 中):

Public Shared Sub runApplication(ByVal appString As String)
  Dim lines As String() = regex.Split(appString, ";(?!.*(\}|""|')|(\{|""|'))")
  Const iStart$ = "^[\t\s]*"
  Const iSpaceTab = "[\t\s]*"
  Const iProperty As System.Text.RegularExpressions.RegexOptions = Text.RegularExpressions.RegexOptions.None
  'set Text.RegularExpressions.RegexOptions.IgnoreCase to ignore case language
  Dim varList As New Dictionary(Of String, String)
  Dim constList As New Dictionary(Of String, String)

  For i As UInt64 = 0 To lines.Length - 1
     Dim X As String = lines(i)
     lastItem = X
 '........

我正在使用 Visual Basic .NET, .NET 框架 4.5

【问题讨论】:

  • 你用来生成它的代码在哪里?
  • 看起来主要问题是在多行上拆分的字符串被视为多个字符串;将它们重新连接在一起应该相当简单,因此它们是一个字符串(带有换行符)。
  • 我能做些什么来解决它?
  • 查看您希望 ; 作为分隔符但在像 ' 这样的打开和关闭元素之间不希望它成为分隔符表明您几乎需要语法。正则表达式不适用于解析语法,因此请注意,您可能需要进行一些后期处理,因为在您的示例中,正则表达式无法区分第 1 行和第 4 行。

标签: .net regex


【解决方案1】:

与其使用RegEx.Split,不如创建一个与您专门寻找的字符串匹配的模式?例如,这样的事情:

(?<=^|\n|;\s*)({[^}]*}|'[^']*'|.*?)(?=;)

查看working example

那么你需要做的就是让匹配循环通过它们:

For Each m As Match In RegEx.Matches(appString, "(?<=^|\n|;\s*)({[^}]*}|'[^']*'|.*?)(?=;)")
    Dim line As String = m.Value
    ' ...
Next

【讨论】:

  • 你是正则表达式之神?非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
相关资源
最近更新 更多