Manjunath
Manjunath

Reputation: 13

regular expression in groovy to replace string starting with multiple - character

I'm storing the content of a file in a String variable String fileContents = new File('file location').text , string contains multiple lines of data as shown below

 Sample text 
--- Some text---- 
Another Sample text
-- Some more text ------
--Again some more text
More Sample text

Need help in... 1. removing the data which starts with two or more '-' character (w\o quote) till the end of line. 2. removing texts between multiple - character.

So, the expected output should be like

Sample text

Another Sample text

More Sample text

Upvotes: 0

Views: 7669

Answers (2)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

The tricky part is the new-lines. The lines are easy to filter out, but you end up with empty lines. This code:

def s = '''Sample text 
--- Some text---- 
Another Sample text
-- Some more text ------
--Again some more text
More Sample text'''

println s.replaceAll(/(?m)^--.*$/, '')

Produces:

Sample text 

Another Sample text


More Sample text

What you can do is process the String as a List, so that you can drop the offending lines, and then convert it back to a String:

println s.split(/\n/).findAll { !(it =~/(?m)^--.*$/) }.join('\n')

Produces:

Sample text 
Another Sample text
More Sample text

Upvotes: 0

anubhava
anubhava

Reputation: 785156

You can search using this regex:

^\s*--+.*$

And replace by empty string. Make sure to use multiline flag.

RegEx Demo

Code:

str = str.replaceAll("(?m)^\\s*--+.*$", "");

Upvotes: 1

Related Questions