How can I extract a substring enclosed in double quotes in Perl?

I'm new to Perl and regular expressions, and it's hard for me to extract a string enclosed in double quotes. For example,

"Stackoverflow is

awesome "

Before extracting the lines, I want to check if there is an end of line of all the text in the variable:

if($wholeText =~ /\"$/)   #check the last character if " which is the end of the string
{
   $wholeText =~ s/\"(.*)\"/$1/;   #extract the string, removed the quotes
}

My code does not work; he does not fall within the condition if.

+3
source share
4 answers

You need to do:

if($wholeText =~ /"$/)
{
    $wholeText =~ s/"(.*?)"/$1/s;
}

.does not match newlines unless you use a modifier /s.

You do not need to hide quotation marks as you do.

+7
source

, "m" , , . :

$wholeText =~ s/\"(.*)\"/$1/m;   #extract the string, removed the quotes

... "", , (. *) . :

"The quick brown fox," he said, "jumped over the lazy dog."

... "The" "dog". , , , . . , , " ".

:

$wholeText =~ s/\"([^"]*)\"/$1/m;

:

$wholeText =~ s/\"(.*?)\"/$1/m;

" , , , , ". " , , ". ? () , . , .

, CSV ( "Comma Separated Values" ), .
+4

( , ), \z anchor:

 if( $wholeText =~ /"\z/ ) { ... }

. . , :

 $wholeText =~ s/"(.*?)"\z/$1/s;

, . ? ?

+3

'm' .

if ($wholeText =~ m/\"$/m) # First m for match operator; second multi-line modifier
{
     $wholeText =~ s/\"(.*?)\"/$1/s;   #extract the string, removed the quotes
}

, , , . ( ), . .

@chaos 's' modifier. :

. , "^" "$" .

  • s

. , "." , , .

Used together as / ms, they allow "." match any character, while preserving the values ​​"^" and "$", respectively, immediately after and immediately before the characters of the new line inside the line.

+1
source

Source: https://habr.com/ru/post/1718665/


All Articles