2016-05-12 63 views
-3

我有一个python脚本:如何使用Ruby正则表达式来搜索路径并将其替换?

speaking_to_sublime.py

import sublime, sublime_plugin 

class SpeakingToSublime(sublime_plugin.WindowCommand): 
    def run(self): 
     self.window.run_command("advanced_new_file_new",{"initial_path": "/Users/max/test/test2/"}) 

,我试图写一个Ruby脚本,执行以下操作:

desired_path = "/some/path/i/want/to/go/" 
# read speaking_to_sublime.py 
# parse through it and store as a string 
# store contents of speaking_to_sublime.py in here 
speaking_to_sublime_string = "" 
# use regular expressions to somehow replace: 
# "/Users/max/test/test2/" with desired_path 
# write speak_to_sublime_string to speaking_to_sublime.py 

我能想出如何使用ruby读写文件,但是如何使用正则表达式来获取"/Users/max/test/test2/"并将其替换为"/some/path/i/want/to/go/"

+0

为什么不只是将Python脚本更改为接受路径参数? –

回答

0

我试图修改python脚本,因为我不确定如何从命令行传递参数以崇高。作为一种解决方法,我打算制作一个自定义插件,并在我使用来自命令的崇高命令调用该命令之前,通过将它们写入文件来更改“参数”。这听起来很迂回,但我还不知道escaping the quotes当你从崇高的cli传递参数。我居然还没有测试它是否会仍然工作,但任何人谁是有兴趣在适当的正则表达式可以可以发现on rubular

re = /"initial_path": "(.+)"/ 

为什么我试图用regexs的原因是因为路径将改变一切从那时起,我基本上计划在每次调用时重新编写插件。我通过观看精彩演讲后学会了如何做Nell Shamrell

0

看来这就是你想要做的?

python_file_path = 'path/to/speaking_to_sublime.py' 
text    = File.read(python_file_path) 
path_to_replace = "/Users/max/test/test2/" 
desired_path  = "/some/path/i/want/to/go/" 

new_text = text.gsub(path_to_replace, desired_path) 

File.open(python_file_path, "w") {|file| file.write(new_contents) } 

你并不需要一个正则表达式来代替直接的文字,gsub可以接受一个字符串做同样的事情,具有更好的性能。如果你坚持使用正则表达式,你可以使用path_to_replace = /\/Users\/max\/test\/test2\//

相关问题