Developer
Developer

Reputation: 6350

Regex to remove data between 2 semicolns perl

A string have data with semicolons now i want to remove all the data within the 2 semicolons and leave the rest as it is. I am using perl regex to remove the unwanted data from the string:

String :

$val="Data;test is here ;&data=1dffvdviofv;&dt&;&data=343";

Now we want to remove all the data between each semicolons ,throughout the string :

$val=~s/(.*)(\;.*\;)(.*)$/$1$3/g;

But this is not working for me. Final out should be like below :

Data &data=1dffvdviofv&data=343

Upvotes: 2

Views: 81

Answers (1)

haukex
haukex

Reputation: 3013

One of the problems is that .* is greedy, that is, it will consume as much as it can. You can make it non-greedy by writing .*?, but that alone won't fix your regex since you've anchored it to the end of the string with $. Personally I don't think there is a need for the capture groups, you can just write

$val =~ s/;.*?;//g;

I'm assuming that the extra space in your expected output (Data &data...) is a typo.

You might also want to consider using a proper parser for whatever data format this is.

Upvotes: 4

Related Questions