Reputation: 5629
I was wondering if there was a way to use Regular expressions to remove n occurrences of characters right before n matches of [removebefore]
Might be unclear, but an example explains everything:
This is a teststring[removebefore][removebefore][removebefore]. blablabla[removebefore][removebefore]
should be changed into
This is a teststr. blablab
Of course this can be done by matching and replacing /.\[removebefore\]/
a dozen of times, but is there a way to do this in one regexp?
EDIT:
I was trying to do this in PHP. And indeed I am searching for a regular expression that matches [anychar]{n}\[removebefore\]{n}
where n is the number of removebefore's.
Upvotes: 0
Views: 945
Reputation: 36262
One possible solution using perl
Regular expression:
s<([^\[]+)((?:\[removebefore\])+)><substr( $1, 0, length($1) - scalar(split(/]\[/, $2)) )>ge
Test:
Content of script.pl:
use warnings;
use strict;
while ( <DATA> ) {
s<([^\[]+)((?:\[removebefore\])+)><substr( $1, 0, length($1) - scalar(split(/]\[/, $2)) )>ge;
print;
}
__DATA__
This is a teststring[removebefore][removebefore][removebefore]. blablabla[removebefore][removebefore]
Running script:
perl script.pl
And result:
This is a teststr. blablab
Upvotes: 1
Reputation: 1101
As far as I know, regex match things. They don't delete or modify input.
A pretty straightforward algorithm would be:
1 - Read your input counting the characters until you get to a [removebefore].
2 - When you get to [removebefore], count the number of [removebefore] in another variable.
3- Subtract the number of [removebefore] from the number of characters and save it in a variable, let's call it "n".
4 - Go again through your input, printing the first "n" number of characters.
There is some error handling to be done in this algorithm, but that's basically it.
Upvotes: 0