我正在尝试使用正则表达式将变量(x)设置为文本文件中的字符串。
在我搜索的文件中,存在多行代码,其中一行是票号WS ########。看起来像这样
〜文件〜
out.test
WS12345678
something here
pineapple joe
etc.
〜代码〜
def foundSomething(m):
console.write('{0}\n'.format(m.group(0), str(m.span(0))))
editor1.research('([W][S]\d\d\d\d\d\d\d\d)', foundSomething)
通过我的研究,我设法让上面的代码工作,当文件中存在相应的文本时,它会将WS12345678输出到控制台。
如何将WS12345678放入变量中,以便用相应的数字保存该文件?
修改 把它放在伪代码中我试图
x = find "WS\d\d\d\d\d\d\d\d"
file.save(x)
解决方案 谢谢@Kasra AD的解决方案。我能够创建一个解决方法。
import re #import regular expression
test = editor1.getText() #variable = all the text in an editor window
savefilename = re.search(r"WS\d{8}",test).group(0) #setting the savefile variable
console.write(savefilename) #checking the variable
要使用PythonScript插件在notepad ++中查找文件中的特定字符串,您可以将所有内容从1个编辑器拉到字符串中并对其进行正则表达式搜索。
答案 0 :(得分:1)
您需要在函数中返回结果,然后只需赋值给变量:
def foundSomething(m):
return console.write('{0}\n'.format(m.group(0), str(m.span(0))))
my_var=foundSomething(input_arg)
并且为了提取您想要的字符串,您可以使用以下正则表达式:
>>> s="""out.test
... WS12345678
... something here
... pineapple joe"""
>>> import re
>>> re.search(r'WS\d{8}',s).group(0)
'WS12345678'