【问题标题】:Python regular expression: search .txt file stringPython正则表达式:搜索.txt文件字符串
【发布时间】: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.sub11 替换为 12,但也会导致 "custom11" 更改为 "custom12"。有没有办法改变行中的子字符串?

【问题讨论】:

    标签: python regex


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!第二部分呢 - 是否可以使用 re.sub 仅将子字符串替换为 11 到 12?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多