Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Iterate through String with multiple lines

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 #.

Upvotes: 8

Views: 33759

Answers (7)

jozh
jozh

Reputation: 2692

data.eachLine {
    if (!it.startsWith( '#' )
        println it
}

Upvotes: 13

Thomas Traude
Thomas Traude

Reputation: 850

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"]

Upvotes: 1

epidemian
epidemian

Reputation: 19219

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

Upvotes: 0

supersam654
supersam654

Reputation: 3244

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.

Upvotes: 0

tim_yates
tim_yates

Reputation: 171084

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' ]

Upvotes: 14

SJ Z
SJ Z

Reputation: 101

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);
  }
}

Upvotes: 10

sradforth
sradforth

Reputation: 2186

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("#") .

Upvotes: 1

Related Questions