如何使用Ruby正则表达式搜索路径并替换它?

时间:2016-05-12 10:20:17

标签: ruby regex

我有一个python脚本:

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/"

2 个答案:

答案 0 :(得分:1)

这似乎是你正在尝试做的事情?

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\//

答案 1 :(得分:0)

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

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

我试图使用正则表达式的原因是因为路径会一直在变化,因为我基本上计划在每次调用时重新编写插件。在Nell Shamrell

观看精彩演讲之后,我学会了如何做到这一点
相关问题