I have a Perl script, that's supposed to match this string:
Sometimes, he says "hey fred, what's up?"
It says if it found fred at the beginning, end, or middle of the word, or if it just found "fred". So it matches Alfred, and Frederich.
Well, in this string, it's supposed to say it found fred on its own, but it's saying it found it at the beginning of a word. Here is the regex for the beginning-of-word-fred, (it's in an if-elsif ladder going beginning of word, end of word, just fred, middle of word):
if(/.*\s+[fF][rR][eE][dD][^ \t\r\n,.:;'"].*/){
print "found fred at beginning of a word:\n $_\n";
I used [^ \t\r\n,.:;'"] instead of \S incase the word is followed by some punctuation. Obviously it's not an exhaustive list of punctuation, but it doesn't matter for this example since it's followed by a comma.
this is in a foreach loop... If it means anything, This is exercise 7-1 in Learning Perl 5th ed.
the exercise in the book is to write a Perl program to find "fred" in a list of words. Then it asks, does the script find fred in "Frederich" or "Alfred?" And then it says to write a text file that talks about Fred Flinstone and his friends, and use it as an input to the script.
I figured it out, sort of:
I must have changed something while writing the question that I forgot about: I tested it again and instead of matching the beginning of a word, it just said it found it anywhere. So the problems wasn't that it thought it was at the beginning of a word, it was that it thought it wasn't the only thing in the word. I added [,.:;'"]?\s+ to the code which matches "fred" as a whole word and it worked. I guess I should have thought about it a little more before asking :)
You can use \b for word boundaries and \w for word characters and also, the /i modifier for case insensitivity is cleaner than using [fF] etc.
Something like:
if ($st =~ m{\b fred \w+ }xi) {
print "Found fred at the beginning of a word";
} else {
print "Not found";
}
If you need to look for 'fred' as a word itself, then use \b fred \b.
I'd recommend having a read of http://perldoc.perl.org/perlre.html
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