Regex: match string from Word to Word

I want to extract a string from a piece of text. This line should begin at the end of the line.

Example:

Word 1 = "Hello"
Word 2 = "World"

Text

Hello, this is a sentence. The whole World can read this. What World? 

Part of the text I want to extract:

 Hello, this is a sentence. The whole World 

What regular exception should I use to retrieve a string.

Note: the string "World" occurs twice.

thanks

+4
source share
2 answers
 ^\bHello\b.*?\bWorld\b 

Where is the "." also matches the new line! Pay attention to the boundaries of the words \ b , you do not want to match anything that is not exactly Hello or World, as if these words were part of other words.

 if ($subject =~ m/^\bHello\b.*?\bWorld\b/s) { $result = $&; } 

Notice the s change, which indicates

.

to match newlines.

+2
source

The easiest option is to use a lazy quantifier ( *? ). This will correspond to the first greeting to the first world. (remember the /s flag, for the dot, that's it)

 Hello.*?World 

This can be a problem if you do not want the capture text to contain Hello . More hidden option:

 Hello(?:(?!Hello|World).)*World 

or

 Hello(?:(?!Hello).)*?World 
0
source

All Articles