我有一个如下所示的文本文件
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"
。有没有办法更改行中的子字符串?
最佳答案
在正则表达式中,.
表示任何单个字符。使用\.
.
if re.search('\.txt', line):
print(re.sub("11", "12", line), end='')
关于Python正则表达式: search . txt文件字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13498993/