Iterating over multiple-line rows

I have some data:

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

How can I get the “interesting part” of this? So basically all the lines starting with C #.

+2
source share
7 answers

One Groovy option:

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

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

assert lines == [ 'finally interesting text' ]
+3
source

Use the separation method to get the substrings, and then verify that each of them starts with "#" or not. For instance:

String[] splitData = data.split("\n");
for (String eachSplit : splitData) {
  if (!eachSplit.startWith("#")) {
    print(eachSplit);
  }
}
+4
source

\n split

, # String.startsWith("#") .

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

(\n), , "#".

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

, Java.

0

A regex-based solution that does not require converting the input string to a list:

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

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

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

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

PS: Regexps FTW! = P

0
source

Here is the solution using the Groovy 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"]
0
source

Source: https://habr.com/ru/post/1658565/


All Articles