Python比较两个字符串校验行顺序后提取新增行的实现方法
Python 实现按顺序校验的行增量提取功能
原代码问题分析
你当前的实现使用集合存储行,存在两个致命缺陷:
- 集合是无序结构,完全无法校验旧行的出现顺序是否符合要求
- 集合会自动去重,当旧字符串存在重复行时逻辑会完全失效
实现思路
采用双指针遍历法实现顺序校验,同时收集新增行:
- 将新旧两个字符串按换行符
\n拆分为行列表 - 分别用两个指针指向旧行列表的待匹配位置、新行列表的当前遍历位置
- 逐行遍历新行列表:
- 当前新行与旧行待匹配位置内容一致时,两个指针同时后移,完成当前旧行的匹配
- 内容不一致时,将当前新行计入新增列表,仅后移新行指针
- 遍历结束后校验:如果旧行指针已经走完了整个旧行列表,说明所有旧行都按顺序完整出现在新字符串中,返回新增内容;否则返回None
完整实现代码
def get_addition(old: str, new: str) -> str | None: old_lines = old.split('\n') new_lines = new.split('\n') old_idx = 0 old_len = len(old_lines) added_lines = [] for line in new_lines: if old_idx < old_len and line == old_lines[old_idx]: old_idx += 1 else: added_lines.append(line) # 只有所有旧行都按顺序匹配完成才返回新增内容 if old_idx == old_len: return '\n'.join(added_lines) else: return None
测试验证
测试示例1
输入:
a = """Line one And line two And this would be line three""" b = """Line one And line two An added line! And this would be line three""" print(get_addition(a, b))
输出:An added line!,符合预期。
测试示例2
输入:
a = """Line one And line two And this would be line three""" b = """Line one And line two (but changed!) An added line! And this would be line three""" print(get_addition(a, b))
输出:None,符合预期。
边界场景兼容
- 旧字符串为空时,会返回整个新字符串内容
- 新增行出现在旧行的最前面、中间、末尾场景都可正确识别
- 旧字符串存在重复行时也可正确按顺序匹配
内容的提问来源于stack exchange,提问作者tol
相关产品推荐
相关产品推荐

