如何捕获包含指定字符和子字符串的固定长度字段的行?在这种情况下:
输入:
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)'
但这似乎是一个完全错误的方向
答案 0 :(得分:2)
我强烈建议不要使用单一的正则表达式。最好将你的行切成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
测试live on regex101.com。请注意,只有第2行和第3行满足您所述的要求。