blaughli
blaughli

Reputation: 527

How to grab part of a line in Groovy

I've got lines of text that look like this:

2011-11-08 10:43:47,153 INFO [ScanService thread] [SourceNode] scanning /mongo/db/matcher.cpp

I want to parse them, grabbing only the time value 10:43:47,153

How can one do this? Wildcards...?

Upvotes: 2

Views: 214

Answers (4)

Tiago Fernandez
Tiago Fernandez

Reputation: 1473

log = '''
2011-11-08 08:13:16,121 INFO [ScanService thread] [SourceNode] scanning /mongo/db/matcher.cpp
2011-11-08 09:32:42,102 INFO [ScanService thread] [SourceNode] scanning /mongo/db/matcher.cpp
2011-11-08 10:43:47,153 INFO [ScanService thread] [SourceNode] scanning /mongo/db/matcher.cpp
'''

matcher = (log =~ /\d{2}:\d{2}:\d{2},\d{3}/)

matcher.count.times {
  println matcher[it]
}

gives you:

08:13:16,121
09:32:42,102
10:43:47,153

Upvotes: 1

Jonny Heggheim
Jonny Heggheim

Reputation: 1453

If the date and time is fixed width I would just grab the time value like this:

def s = '2011-11-08 10:43:47,153 INFO [ScanService thread] [SourceNode]'
assert s[11..22] == '10:43:47,153'

Upvotes: 1

Michael Easter
Michael Easter

Reputation: 24468

Consider something like:

def s = "2011-11-08 10:43:47,153 INFO [ScanService thread] [SourceNode]"
def tokens = s.split(" ")
def time = tokens[1]
println time

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160191

I would just split on spaces, or if the date formatting is constant width, use a substring.

A regular expression would also work, but if it's not necessary, I wouldn't bother.

Upvotes: 1

Related Questions