正则表达式,用于解析以空格分隔的数据

时间:2009-06-18 21:13:40

标签: regex vb.net

我已编写代码将一些数据拉入数据表并进行一些数据重新格式化。我需要帮助将一些文本拆分成适当的列。

案例1 我有这样的数据格式,我需要分成两列。

ABCDEFGS     0298 MSD
SDFKLJSDDSFWW         0298 RFD

我需要第1列中数字之前的文本以及第2列中空格之后的数字和文本。文本和数字之间的空格数量会有所不同。

案例2数据我有这样的数据,我需要分成3列。

00006011731 TAB FC 10MG 30UOU
00006011754  TAB FC 10MG 90UOU
00006027531  TAB CHEW 5MG 30UOU
00006071131  TAB CHEW 4MG 30UOU
00006027554  TAB CHEW 5MG 90UO
00006384130  GRAN PKT 4MG 30UOU
  1. 列是前11个字符,很容易
  2. 第2列应包含前11个字符之后的所有文本,但不包括第一个数字。
  3. 最后一列是第2列之后的所有文字

4 个答案:

答案 0 :(得分:2)

我会用这些表达式来做:

(?-s)(\S+) +(.+)

(?-s)(.{11})(\D+)(.+)


在正则表达式评论模式中细分,这些是:

(?x-s)    # Flags: x enables comment mode, -s disables dotall mode.
(       # start first capturing group
 \S+     # any non-space character, greedily matched at least once.
)       # end first capturing group
[ ]+     # a space character, greedily matched at least once. (brackets required in comment mode)
(       # start second capturing group
 .+      # any character (excluding newlines), greedily matched at least once.
)       # end second capturing group

(?x-s)    # Flags: x enables comment mode, -s disables dotall mode.
(       # start first capturing group
 .{11}   # any character (excluding newlines), exactly 11 times.
)       # end first capturing group
(       # start second capturing group
 \D+     # any non-digit character, greedily matched at least once.
)       # end second capturing group
(       # start third capturing group
 .+      # any character (excluding newlines), greedily matched at least once.
)       # end third capturing group


('dotall'模式(标记s)表示.匹配所有字符,包括换行符,因此我们必须禁用它以防止在最后一个组中进行过多匹配。)

答案 1 :(得分:1)

假设您知道如何处理VB.NET代码以获取分组(匹配)并且您愿意自己从分组中删除多余的空格

案例1的正则表达式是

(.*?\s+)(\d+.*)
    .*? => grabs everything non greedily, so it will stop at the first space
    \s+ => one or more whitespace characters

    These two form the first group.

    \d+ => one or more digits
    .* => rest of the line

    These two form the second group.

案例2的正则表达式是

(.{11})(.*?)(\d.*)
    .{11} => matches 11 characters (you could restrict it to be just letters
             and numbers with [a-zA-Z] or \d instead of .)

    That's the first group.

    .*? => Match everything non greedily, stop before the first 
           digit found (because that's the next regex)

    That's the second group.

    \d.* => a digit (used to stop the previous .*?) and the rest of the line

    That's the third group.

答案 2 :(得分:0)

我会使用Peter Boughton的正则表达,但要确保你有。匹配换行关闭。如果启用,请确保在最后添加$:)

贪婪的正则表现会更好。

答案 3 :(得分:-1)

您呈现的数据类型的最简单方法是将行拆分为空格中的字段,然后重新组合您想要的内容。 Regex.Split(line, "\\s+")应该返回一个字符串数组。这对于更改字段中的字符串也更加健壮,例如,如果在第二种情况下,行显示为“00006011731 TAB 3FC 10MG 30UOU”。