in reply to match whitespace or beginning/end of string

What's wrong with \b? It's only needed at the beginning, since you have the closing quote to mark the end. (UPDATED below with fancier pattern)

Test code:

#!/usr/bin/perl use strict; use warnings; use diagnostics; my $alpha = qq(alpha="first"); my $beta = qq(beta="second"); my $gamma = qq(gamma="third"); my $s1 = qq($alpha $beta $gamma); my $s2 = qq($alpha $gamma $beta); my $s3 = qq($beta $alpha $gamma); #my $pat = qr/\b(beta="second")/; my $pat = qr/(?:\A|\s)(beta="second")(?:\s|\Z)/; print "s1: \'$s1\', match=".($s1 =~ $pat ? $1 : "nada")."\n"; print "s2: \'$s2\', match=".($s2 =~ $pat ? $1 : "nada")."\n"; print "s3: \'$s3\', match=".($s3 =~ $pat ? $1 : "nada")."\n";
Produces:
s1: 'alpha="first" beta="second" gamma="third"', match=beta="second" s2: 'alpha="first" gamma="third" beta="second"', match=beta="second" s3: 'beta="second" alpha="first" gamma="third"', match=beta="second"
Updated: Removed half the test cases, since there's really only 3 possibilities. Also added fancy pattern that ensures either start/end of string or space is present.

Replies are listed 'Best First'.
Re^2: match whitespace or beginning/end of string
by azadian (Sexton) on Oct 30, 2009 at 13:17 UTC
    Works fine for beta, but the same code would not work for alpha. The point is, I don't know the location in the string of the word I'm matching. You're right that, in this case, I don't need to worry about the end of string. But still, I'd like to be able to give my users a general-purpose rule which works even without the quotes.
      See updated code above using fancier pattern. (Why do you think think the original would not work for alpha?)
        Yes, the improved code is fine, and covers all cases. However, the goal is to have code which is fine and covers all cases AND IS SIMPLER. I want simple because I need to recommend this to testers who don't know necessarily know what a regular expression is. I can tell them to stick in a \b at the beginning and end of each word to be matched, and I can even explain it to them. Unfortunately, \b doesn't always work. The more complicated expressions such as you used (and I suggested) are not so easy to recommend or explain. I just want to know if there is some simple way to do what seems like a simple task.