【发布时间】:2012-11-21 17:41:31
【问题描述】:
我有一个像这样的文本文件
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"行中将"11"替换为"12",但仅限于文件路径中,而不是"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"。有没有办法改变行中的子字符串?
【问题讨论】: