问题描述
我想从文件中替换字符串。
i有这样一行:
i want to replace string from a file.i have a line like this:
qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz
我想从数据中取代所有字符串使用空格登录
i want to replace all string starting from data to login with spaces
我试试这个我只能替换字符串,是否有一种方法可以替换字符串的起始和终止符?
i try this i can only replace the string, is there a way to replace with a starting and endpoint for string?
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
def fileText = source.text
def filedest = dest.text
for ( index in 1..9 ) {
fileText = (fileText =~ /data/).replaceFirst("")
推荐答案
此代码具有一个锚定版本(至 {
)的正则表达式的:
This code has an anchored version (to {
) of the regex:
def fileText = '''\
qwe{data:"dede-dddd-ssss",login:"user",display:"screen1"},abc,xyz
...
qwe{data:"data2",login:"user2",display:"screen2"},abc,xyz
...
qwe{data:"data3",login:"user3",display:"screen3"},abc,xyz\
'''
fileText = fileText.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '')
println fileText
输出:
Output:
qwe{display:"screen1"},abc,xyz
...
qwe{display:"screen2"},abc,xyz
...
qwe{display:"screen3"},abc,xyz
试试
更新
如果您正确理解您的请求:以下代码读取 source
( c:\\sq\\file1.txt
)并将修改后的文本放入目标文件 dest
( c:\\sq\\file2.txt
):
If a understand correctly your request: this following code read the input text from source
(c:\\sq\\file1.txt
) and put the modified text into destination file dest
(c:\\sq\\file2.txt
):
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
dest.write(source.text
.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '') )
这篇关于groovy用空间替换文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!