Regex trick, how to remove one quoted content from a string?

K

Kelvin

Hi, there:

In some portions of my string, there are many quoted contents separated by ;
sign.
What I need is retain only one quoted content and remove the extras.

How can regex do this job?

For example,
===========================================
$str = ___d event; "he missed the test and had to take a makeup"; "the two
teams played a makeup one week later";;cosm___
===========================================
$new_str = ___d event; "he missed the test and had to take a
makeup";;cosm___



Thank you in advance.
 
J

John W. Krahn

Kelvin said:
In some portions of my string, there are many quoted contents separated by ;
sign.
What I need is retain only one quoted content and remove the extras.

How can regex do this job?

For example,
===========================================
$str = ___d event; "he missed the test and had to take a makeup"; "the two
teams played a makeup one week later";;cosm___
===========================================
$new_str = ___d event; "he missed the test and had to take a
makeup";;cosm___

1 while $str =~ s/("[^"]*");[^"]*"[^"]*"/$1/;


John
 
A

Anno Siegel

Kelvin said:
Hi, there:

In some portions of my string, there are many quoted contents separated by ;
sign.

....plus possibly blanks, it seems. Please be precise in your
specification.
What I need is retain only one quoted content and remove the extras.

How can regex do this job?

Here is one way (untested). Separate the string into three parts:
What comes before the first '"', everything from the first to the last
'"', and the remainder. Split the middle part on /; */ or whatever
the exact separator is. Select the one you want to keep (I'll assume
the first one). Put everything together again.

my ( $head, $mid, $tail) = $str =~ /^([^"]*)(".*")([^"]*)$/;
my $sel = ( split /; */, $mid)[ 0]; # select the first quoted string
my $new_str = join '', $head, $sel, $tail;

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top