首页 文章

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

提问于
浏览
1

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

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"

  • ".txt" 行上用 "12" 替换 "11" ,但仅在文件路径中,而不是在 "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.sub12 替换 11 ,但也会导致 "custom11" 变为 "custom12" . 有没有办法改变行中的子字符串?

1 回答

  • 1

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

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

相关问题