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 #.
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).
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.
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
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.
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' ]
data.eachLine {
if (!it.startsWith( '#' )
println it
}
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);
}
}
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("#") .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With