Python:将长字符串与特殊字符和空格匹配,然后在开头添加两个字符
我不知道如何解决这个问题,我试图在一个有大量空格和特殊字符的文本文件中匹配这个长字符串,并将这些字符附加到前面,即。 “//”
我需要匹配这一行:
$menu_items['gojo_project'] => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),
并将其变成这样:
//$menu_items['gojo_project'] => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),
注意我只是在前面添加了两个“/”字符。
我尝试使用 re.escape 来格式化字符串,但它真的很长并且仍然抛出语法错误。我使用“re”以正确的方式处理这个问题吗?或者是否有一种更好的Pythonic方法来匹配文本文件中这样的字符串并添加到它前面?
编辑:忘记提及我需要在线编辑文件。简而言之,它是一个很长的 php 脚本,我试图找到该行并将其注释掉(即 //)。所以,我不能真正使用一些建议的解决方案(我认为),因为他们将修改写入单独的文件。
I'm not sure how to approach this, i'm trying to match this long string in a text file that has lots of whitespace and special characters and append the characters to the front ie. "//"
i need to match this line:
$menu_items['gojo_project'] => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),
and turn it into this:
//$menu_items['gojo_project'] => array('http://www.gojo.net/community/plugin-inventory/ops-gojo/gojo', 'gojo',3),
notice i just prepended two '/' character.
I tried using re.escape to format the string, but its just really long and still throw sytax error. Am i going about this the right way using 're' ? or is there a better pythonic way to match a string like this one in a text file and prepend to it?
Edit: Forgot to mention that i need to edit the file in-line. In short, its a long php script that i'm trying to find that line and comment it out (ie. //). So, I cant really use some of the proposed solutions(i think) since they have it writing the modification to a separate file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
fileinput
它可以让你读取文件并就地重写行:Try
fileinput
it will let you read over a file and rewrite lines in place:如果您尝试精确匹配该字符串,那么使用字符串相等运算符而不是正则表达式会更容易。
If you're trying to match exactly that string, it would be easier just to use the string equality operator, rather than regular expressions.