Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eclipse - regex: replace multiple group

someText
1
2
3
4
moreText

I would like to add a prefix before each digit.

but using (\w+\R)(\d+\R)+(\w+) and \1prefix\2\3 will only prefix the last digit and erase the others.

Is there a way to do it with a single regex or should i write a script on the side?

like image 438
Garagos Avatar asked Oct 18 '10 13:10

Garagos


1 Answers

The problem with your regex is the use of greedy matching in the (\d+\R)+, specifically the last +. That reads, "match this group as many times as you can so long as it doesn't cause the miss of a match". So for your text it gobbles up 1, 2, 3, and 4 before it can't gobble any more and puts the last match into the second capture group. Obviously, it's in the nature of regex engines to be unable to express variadic groups, how would you address them anyway? So the short answer, I think is that regexes are the wrong tool for a fully automated process and you'll have to write a script.

However, for a slightly less automated process that still incorporates your surrounding text, you could try

find: (\w+\R)((?:\d+\R)+)(\w+)
replace: \1prefix\2\3

We wrap the second group plus it's greedy modifier in an extra set of capturing parens and enclose the actual matching text in a non-capturing group. Now, we have the full set of digits in their own group and can add the prefix to the first one. The interesting side effect of this is that the first number then matches the first group (\w+\R) and if you run the find/replace again it hits the next number in the line until it no longer matches.

This way, you should be able to run through your files at least only hitting the areas you are interested in adding this prefix to and it shouldn't take nearly as long as finding every digit in every file.

like image 194
Tim Visher Avatar answered Sep 21 '22 15:09

Tim Visher