I have a string that covers several lines. I need to extract the text between two strings. For example:
Start Here Some example
text covering a few
lines. End Here
I need to extract the string, Start Here Some example text covering a few lines.
How do I go about this?
User can create a multiline string using the single(”) quotes and as well as with double quotes(“”). Using double quotes cause variables embedded in the string to be replaced by their content while in single quotes variables name remained the same.
Solution. Use /m , /s , or both as pattern modifiers. /s lets . match newline (normally it doesn't). If the string had more than one line in it, then /foo.
That default can be changed to add matching the newline by using the single line modifier: for the entire regular expression with the /s modifier, or locally with (? s) (and even globally within the scope of use re '/s' ).
The Binding Operator, =~ Matching against $_ is merely the default; the binding operator ( =~ ) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_ .
Use the /s
regex modifier to treat the string as a single line:
/s Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.
$string =~ /(Start Here.*)End Here/s;
print $1;
This will capture up to the last End Here
, in case it appears more than once in your text.
If this is not what you want, then you can use:
$string =~ /(Start Here.*?)End Here/s;
print $1;
This will stop matching at the very first occurrence of End Here
.
print $1 if /(Start Here.*?)End Here/s;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With