Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Match String From Word to Word

Tags:

regex

I want to extract a string from a piece of text. This string must start end end with a certain string.

Example:

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

Text:

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

The piece of text i want to extract is:

Hello, this is a sentence.
The whole World

What kind of regular exception should i use for extraction of the string.

Note: the string 'World' occurs twice.

Thanks

like image 346
Mats Stijlaart Avatar asked Oct 23 '11 11:10

Mats Stijlaart


1 Answers

^\bHello\b.*?\bWorld\b

Where the "." also matches newline! Note the word boundaries \b, you don't want to match anything which is not exactly Hello or World, as if those words were part of other words.

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

Note the s modified which instructs

.

to match newline characters too.

like image 82
FailedDev Avatar answered Sep 19 '22 20:09

FailedDev