Using a regular expression to get list of objects

Hello,

I thought I came up with a brilliant idea to use a regular expression to match
a list of objects in a root file - but of course all brilliant ideas have already been
thought of. I note that a class “TRegexp” already exists (I was going to use
boost::regex). But then wading into the documentation on TDirectory, TKey, TIter,
etc. got me lost quickly. So I’ll just ask:

What’s the easiest way to get a list of all objects (histograms specifically) that match
a regular expression in a root file? The regular expression might include directory
separators, i.e., ‘/’ if it’s feasible.

Thanks!
-Phil D.

see example below listing all keys “h*” in file hsimple.root

Rene

void reg() { TFile f("hsimple.root"); TString reg = "h*"; TRegexp re(reg,kTRUE); TIter next(f.GetListOfKeys()); TKey *key; while ((key= (TKey*)next())) { TString st = key->GetName(); if (st.Index(re) == kNPOS) continue; key->Print(); } }

Thanks, Rene,
What if I had two directories in the root file, each containing a histogram with the same name - i.e., I wanted to include the full “subdir1/subdir2/object” specification in the regular expression?
Regards,
-Phil D.

Hi,

You would need to loop on the TKey and recurse into the (sub)directories and reconstruct the full name before making the regex match.

Cheers,
Philippe.

Thanks, Philippe, I was afraid of that…
-Phil D.

[quote=“pcanal”]You would need to loop on the TKey and recurse into the (sub)directories and reconstruct the full name before making the regex match.
[/quote]

This is an opinion and may not be for everybody, but personally I’d use PyRoot to do things like this as I find that it can be a lot more flexible than C++.

(Anything you can do in Python you can do in C++, but not necessarily as easily).

Good luck!
Charles