繁体   English   中英

python regex固定长度字段女巫指定的字符和子字符串

[英]python regex fixed length fields witch specified characters and substrings

如何捕获具有固定长度字段(包括指定字符和子字符串)的行? 在这种情况下:

  • 每个字段包含8个字符
  • 第一个文件仅包含“ RBE3”和空格
  • 第三个文件仅包含“ 123”和空格

输入:

123456781234567812345678123... (char numbers)
RBE3    323123       123121
  RBE3  323123   123    121
RBE3    32312300123     121
RBE3    3231231234      121
$ RBE3  323123123       121
R B E3  32312     123   121
     RBE32312       12313

输出将是:

RBE3    323123       123121
  RBE3  323123   123    121
RBE3    32312300123     121

我尝试过:

regex = r'^([RBE3\s]{8}.{8}[123\s]{8}.*\n)'

但似乎是完全错误的方向

我强烈建议不要为此使用单个正则表达式。 最好将您的代码分成8个部分,然后进行验证。

如果您坚持,这可能但很丑陋:

^(\s*RBE3\s*)(?<=^.{8})(.{8})(\s*123\s*)(?<=^.{24})(.*)$

说明:

^            # Start of string (or line, if you use multiline mode)
(\s*RBE3\s*) # Match RBE3, surrounded by any amount of whitespace --> group 1
(?<=^.{8})   # Make sure that we have matched 8 characters so far.
(.{8})       # Match any 8 characters --> group 2
(\s*123\s*)  # Match 123, surrounded by any amount of whitespace --> group 3
(?<=^.{24})  # Make sure that we have matched 24 characters so far.
(.*)         # Match the rest of the line/string --> group 4
$            # End of string/line

在regex101.com上进行实时测试。 请注意,只有第2行和第3行满足您所述的要求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM