groovy用空间替换文件中的数据 [英] groovy replace data from file with space

查看:104
本文介绍了groovy用空间替换文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件中替换字符串。
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

试试在线常规Web控制台

更新

如果您正确理解您的请求:以下代码读取 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用空间替换文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆