aliocee
aliocee

Reputation: 730

Regular expression to match words with word boundary in a sentence using Perl?

Is their a way to match a word in the following sentence with word boundary and should match the words with dash, braket, comma, fullstop etc. at the right or left of the word.

Eg:

 $str = "The quick brown fox (jump) over the lazy dog yes jumped, fox is quick jump, and jump-up and jump.";

how can i match the 4 occurance of the word 'jump' in the sample sentence using perl regular expression?

NOTE: i dont want to match the word 'jumped'.

Upvotes: 1

Views: 4041

Answers (4)

parthi
parthi

Reputation: 156

my @arr = $string =~ m{\bjump\b}g;
print "@arr\n";

Upvotes: 0

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22481

A word boundary ("\b") is a spot between two characters that has a "\w" on one side of it and a "\W" on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a "\W".

-- perldoc perlre > Assertions

foreach($str=~/\b(jump)\b/g){
    print "$1\n";
}

Upvotes: 2

Ωmega
Ωmega

Reputation: 43703

print "$_\n" for $str =~ /\bjump\b/g;

Upvotes: 0

JRFerguson
JRFerguson

Reputation: 7526

my @words = $str =~ m{\bjump\b}g;
print "@words\n";

Upvotes: 4

Related Questions