Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match all lines starting with a specific string

Tags:

regex

groovy

I have this very long cfg file, where I need to find the latest occurrence of a line starting with a specific string. An example of the cfg file:

...
# format: - search.index.[number] = [search field]:element.qualifier
...    
search.index.1 = author:dc.contributor.*
...
search.index.12 = language:dc.language.iso
...
jspui.search.index.display.1 = ANY
...

I need to be able to get the last occurrence of the line starting with search.index.[number] , more specific: I need that number. For the above snippet, that number would be 12.

As you can see, there are other lines too containing that pattern, but I do not want to match those.

I'm using Groovy as a programming/scripting language.

Any help is appreciated!

like image 312
Pieter VDE Avatar asked Oct 16 '25 02:10

Pieter VDE


2 Answers

Have you tried:

def m = lines =~ /(?m)^search\.index\.(\d+)/
m[ -1 ][ 1 ]
like image 82
tim_yates Avatar answered Oct 18 '25 16:10

tim_yates


Try this as your expression :

^search\.index\.(\d+)/

And then with Groovy you can get your result with:

 matcher[0][0]

Here is an explanation page.

like image 25
Christophe Sophy Avatar answered Oct 18 '25 17:10

Christophe Sophy