7

I got some data:

def data = "# some useless text\n"+
        "# even more\n"+
        "finally interesting text"

How can I get the "interesting part" of that? So basically all lines, NOT starting with #.

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

7 Answers7

14

One Groovy option would be:

def data = '''# some useless text
             |# even more
             |finally interesting text'''.stripMargin()

List lines = data.split( '\n' ).findAll { !it.startsWith( '#' ) }

assert lines == [ 'finally interesting text' ]
tim_yates
  • 167,322
  • 27
  • 342
  • 338
13
data.eachLine {
    if (!it.startsWith( '#' )
        println it
}
jozh
  • 2,412
  • 2
  • 15
  • 15
9

Use split method to get substrings then check each one starts with "#" or not. For example:

String[] splitData = data.split("\n");
for (String eachSplit : splitData) {
  if (!eachSplit.startWith("#")) {
    print(eachSplit);
  }
}
SJ Z
  • 91
  • 1
1

How's about splitting the string with \n character via the split function

Now you can just test each string if it starts with # or not via String.startsWith("#") .

sradforth
  • 2,176
  • 2
  • 23
  • 37
1

Here is a solution by using Groovy's meta programming feature (http://groovy.codehaus.org/JN3525-MetaClasses):

def data = "# some useless text\n"+
    "# even more\n"+
    "finally interesting text"

String.metaClass.collectLines = { it ->
    delegate.split('\n').findAll it
}

def result = data.collectLines{ !it.startsWith( '#' )}

assert result == ["finally interesting text"]
Thomas Traude
  • 840
  • 7
  • 17
0

I would split the string based on the newline character (\n) and then ignore the lines that start with "#".

String[] lines = data.split("\n");
for (String line : lines) {
    if (line.startsWith("#") {
        continue;
    }
    //Do stuff with the important part
}

Note that this is pure Java.

supersam654
  • 3,126
  • 33
  • 34
0

A regexp-based solution that does not require to convert the input string into a list is:

def data = '''\
# some useless text
# even more
finally interesting text'''

assert data.replaceAll(/#.*\n/, '') == 'finally interesting text'

If you need to split the input into lines anyways, you can still use regexps if you want to, using the Collection#grep method:

assert data.split('\n').grep(~/[^#].*/) == ['finally interesting text']

PS: Regexps FTW! =P

epidemian
  • 18,817
  • 3
  • 62
  • 71