Reputation: 1279
I'm new in Groovy coding ( I have the stings that hold the ip address and GUID. Sometime the GUID is empty.
For example:
139.14.8.162 b38e34ab-32ad-46b3-961c-17762c1c2957
139.268.15.201
How in Groovy I can get the ip address from the line where the GUID does not exist? In my example I need to skip the line with 139.14.8.162 get the 139.268.15.201
Thank you for your help.
Upvotes: 0
Views: 463
Reputation: 50245
def data = '''139.14.8.162 b38e34ab-32ad-46b3-961c-17762c1c2957
139.268.15.20
139.269.14.201
139.15.9.162 961c-32ad-46b3-961c-17762c1c2957'''
// Poor man's solution if you are sure that you would get IPv4 strings
data.readLines().findAll { it.trim().size() <= 15 }
// A little explicit from above solution
data.readLines().findAll { it.tokenize(/./)[3].trim().size() <= 3 }
// Extensions to previous answers
data.readLines()*.split().findResults { it.size() == 1 ? it[0] : null }
// BDKosher's approach using readLines()
data.readLines()*.split().findAll { it.size() == 1 }.flatten()
// UPDATE: And yes I totally missed JDK 8 Stream implementation
data.readLines()
.stream()
.filter { it.trim().size() <= 15 }
.map { it.trim() }
.collect()
From the frequency of answers you would imagine there are more than one ways to find a solution to a problem in Groovy. Hence the name. :)
I am quite sure you would enjoy the journey.
Upvotes: 1
Reputation: 5883
You don't necessarily need regular expressions to parse the contents.
If you split each line of the config, it should produce arrays with either one or two elements: a one element array for the lines with only an IP, a two element array if the line has both an IP and GUID.
Then it's a matter of grabbing only the one-element arrays.
data.split(/\n/) // convert String into List of Strings (if needed)
.collect { line -> line.split() } // transform each line into an array
.findAll { it.size() == 1 } // select the lines that only had IPs
.flatten() // flatten each 1-element array to get a list of IPs
Upvotes: 0
Reputation: 9885
To get the IP addresses from lines which do not have a GUID...
String
into lines.// Sample data
def data = '''139.14.8.162 b38e34ab-32ad-46b3-961c-17762c1c2957
139.268.15.201
139.269.14.201
139.15.9.162 961c-32ad-46b3-961c-17762c1c2957'''
def ipAddresses = data.split(/\n/).findAll { it ==~ /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ }
// Assertion showing it works.
assert ipAddresses == ['139.268.15.201', '139.269.14.201']
First, data.split(/\n/)
returns a List
containing each line in the String
. Finally, findAll { it ==~ /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ }
traverses the List
and returns all of the entries which match the regular expression.
Upvotes: 1