Python正则表达式:搜索.txt文件字符串

时间:2012-11-21 17:41:31

标签: python regex

我有一个看起来像这样的文本文件

other stuff
set fmri(custom11) "/home/this/is/a/sample_path/to_some/arbitarily/named_11/file-with-othercharacters/file.txt"
other stuff

我想使用Python搜索该文件

  • ".txt"
  • 的所有行
  • "11"替换为"12"行上的".txt",但仅限于文件路径,而不是"custom11"字符串。
  • 我省略了循环逻辑,只关注re.search和re.sub的使用。
if re.search('.txt', line):
   print(re.sub("11", "12", line), end='')

不知何故,re.search找不到.txt。如果我使用:

if re.search('xt', line): 

我得到的大部分行包含文本文件,但也包含其他内容。如何正确查找'.txt'文件行?

此外,在测试时,re.sub会将11替换为12,但也会导致"custom11"更改为"custom12"。有没有办法改变行中的子字符串?

1 个答案:

答案 0 :(得分:1)

在正则表达式中,.表示任何单个字符。使用\.

if re.search('\.txt', line):
   print(re.sub("11", "12", line), end='')
相关问题