perl, strip spaces and double quote character at beginning and at the end of a string

How do I strip spaces and double quote character at beginning and at the end of a string, if the double quote exist?

$string1 = "\"my string1\"";  # => to "my string1"
$string2 = "  \" my string2 \"  "; #=> to " mystring2 "
rgbcofAsked:
Who is Participating?
 
jeromeeConnect With a Mentor Commented:
Please try this:
   s/(^\s*")|("\s*$)//g;
0
 
YellowShoeCommented:
Does '\' specify the part where the string starts/ends. If so you could use that as a delimiter as well.

Using your logic - if double quotes and spaces appear at the start and end of strong
$string1 =~ s/^[ "]*//; # delete all spaces and double quotes 0 0r more occurrences
$string1 =~ s/[ "]*$//;

alternately
$string1 = /^[^"]*([^\\]*)\\".*/$1"/;
0
 
wilcoxonCommented:
This should do it:

$string =~ s{^[\s"]+}{};
$string =~ s{[\s"]+$}{};

Using | as jeromee did above will sometimes work and sometimes not.  For example,

$string =~ s{(?:^[\s"]+)|([\s"]+$)}{};

does not work.
0
[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

 
ozoConnect With a Mentor Commented:
s/^\s*"//,s/"\s*$// for $string1,$string2 ;
0
 
ozoCommented:
$string =~ s{(?:^[\s"]+)|([\s"]+$)}{}g; #works, but the g is required, and it is not as fast as s{^[\s"]+}{} and s{[\s"]+$}{}; separately, if you care about that
also, it does
$string2 = "  \" my string2 \"  "; #=> to "mystring2"
unlike the requested
$string2 = "  \" my string2 \"  "; #=> to " mystring2 "
0
 
jeromeeCommented:
I think the initial answer I posted:
   s/(^\s*")|("\s*$)//g;
works for both strings.
0
 
ozoCommented:
Yes, it does work for both strings.
0
 
wilcoxonCommented:
sigh - yep - I made two mistakes in my comment as ozo pointed out.  I left off the g on the "doesn't work" example (so it does work) and I misread the request so used char classes which are efficient but don't work in this case.

jeromee, yes, your answer worked.  I should have been more clear - I was trying to give a different example that didn't work (and failed at that as well).

Apparently my brain is dead today...
0
 
rgbcofAuthor Commented:
You guys are such perl/regex expert.  I am so jealous.
0
 
jeromeeCommented:
If you play with regex regularly it gets easier, and it quickly loses its "crypticness", I promise!

Good luck.
0
All Courses

From novice to tech pro — start learning today.