简体   繁体   English

使用正则表达式将文件中的子字符串替换为 python

[英]replace sub-string in a file using regex with python

suppose I have a file.txt with line假设我有一个 file.txt 行
aaaa = /bbb/ccc/ddd/eee/fff aaaa = /bbb/ccc/ddd/eee/fff

I would like replace ccc with xxx我想用 xxx 替换 ccc

I have tried next without success我尝试了下一个但没有成功

import re
import fileinput

for line in fileinput.input(file.txt, inplace=True):
    re.sub(r'(ccc)', 'xxx', line)

Try this:尝试这个:


m = re.sub(r'ccc', r'xxx', "/bbb/ccc/ddd/eee/fff")
#OUTPUT: /bbb/xxx/ddd/eee/fff

Almost the same question has been asked already here . 这里已经提出了几乎相同的问题。 In your case the answer would look like this:在您的情况下,答案如下所示:

for line in fileinput.input('file.txt', inplace=True):
    print(re.sub(r'(ccc)', 'xxx', line), end='')

See above link to learn about alternatives and efficiency.请参阅上面的链接以了解替代方案和效率。 (Also note the quotes around file.txt) (另请注意 file.txt 周围的引号)

Short explanation:简短说明:

  • print() in Python prints lines with a newline character by default. Python 中的print()默认打印带有换行符的行。 To prevent this, end='' needs to be specified as keyword argument.为了防止这种情况,需要将end=''指定为关键字参数。
  • r'(ccc)' contains a pair of group parentheses which is not necessary in your case, so you can simply write r'ccc' as already pointed out by the two previous posts. r'(ccc)'包含一对在您的情况下不需要的组括号,因此您可以简单地编写r'ccc' ,正如前两篇文章已经指出的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我们有多个子字符串时,如何使用python替换字符串的特定子字符串? - How to replace specific sub-string of a string using python while we have multiple sub-string? 如何使用python在xml文件的XPATH中搜索部分子字符串或正则表达式 - how to search for partial sub-string or regex in XPATH in a xml file using python Python正则表达式查找子字符串 - Python regex finding sub-string 需要python正则表达式来处理子字符串 - Need python Regex for handling sub-string Python 正则表达式匹配子字符串 - Python Regex Match sub-string 正则表达式搜索模式并替换其前面的模式和子字符串 - Regex to search for a pattern and replace the pattern and sub-string preceding it 在python中使用regex提取多个特定单词之间的子字符串 - Extract sub-string between multiple certain words using regex in python Python正则表达式匹配已匹配的子字符串 - Python Regex matching already matched sub-string 在Python中查找大文件中子字符串的出现 - Finding occurrences of a sub-string in a large file in Python 使用正则表达式从文档中的给定字段中删除子字符串,并在 mongo 中在其前面添加另一个子字符串 - Using regex to remove sub-string from a given field in a document and adding another sub-string in front of it in mongo
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM