Reputation: 18594
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
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
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
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
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
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
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