Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 407
Evgenij Reznik Avatar asked Jan 21 '13 23:01

Evgenij Reznik


People also ask

Is it possible to iterate through a string by line?

It would be better just to read the string from a file, which already allows you to iterate through it as lines. However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline).

How to create a scanner from a multiline string in Java?

The way to create a Scanner from a multiline string is by using the bufio.NewScanner () method which takes in any type that implements the io.Reader interface as its only argument. If you want to read a file line by line, you can call os.Open () on the file name and pass the resulting os.File to NewScanner () since it implements io.Reader.

How to iterate over env variables with multi-line values in Bash?

In modern shells like bash and zsh, you have a very useful `<<<' redirector that accepts a string as an input. So you would do Example how to iterate over env variables with multi-line values: for var in $ (compgen -v | grep -Ev '^ (BASH)'); do echo "$var=$ {!var}" done

What are the downsides of iterating a string in JavaScript?

One downside is you need to convert the string into an array before iterating. If performance really matters in your use case (and it usually doesn’t), it might not be your first choice. As with many techniques in JavaScript, it’s mainly a matter of taste when deciding which one to use.


4 Answers

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' ]
like image 91
tim_yates Avatar answered Nov 12 '22 03:11

tim_yates


data.eachLine {
    if (!it.startsWith( '#' )
        println it
}
like image 28
jozh Avatar answered Nov 12 '22 02:11

jozh


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);
  }
}
like image 24
SJ Z Avatar answered Nov 12 '22 04:11

SJ Z


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

like image 45
sradforth Avatar answered Nov 12 '22 03:11

sradforth