Regex 101 Exercise I2 - Find two words in a string
I2 - Find two words in a string
Find any string that has the following two words in it: “dog” and “vet”
(yes, I know, I didn't get last week's discussion out there. It will be there shortly...)
Comments
Anonymous
December 12, 2005
(?m)(?<string>^.?((bdogb.?bvetb)|(bvetb.?bdogb)).?$)Anonymous
December 12, 2005
permutation is not very scalable, right? what if you need find 3 or 10 words? can you do
^(?=.*dog)(?=.*vet)
?
I would think using IndexOf is simpler and probably results in better performance, no?Anonymous
December 12, 2005
I didn't know about the word boundry thing, cool. Here's my modification:
^.?((b(D|d)og(s?)b.?b(V|v)et(s?)b)|(b(V|v)et(s?)b.?b(D|d)og(s?)b)).?$
which correctly matches (or doesn't match) the following:
I took the dog to the vet.
The vet liked the dog.
There are a lot of dogs that go to vets everyday.
Dog can start a sentence that ends with vet.
Vet can start a sentence that ends with dog
The war veteran ate a hotdog.
This string has a dog but not a you know what.
This string has a vet but not a you know what.Anonymous
December 12, 2005
Come on, you guys are killing me with all these permutations and lower-case/upper-case, you could use RegexOptions.IgnoreCase or (?i)Anonymous
December 12, 2005
The comment has been removedAnonymous
December 13, 2005
Easy... use two regex's.
In Perl:
if (/dog/i and /vet/i)
{
...
}
In C#:
if (
Regex.IsMatch(s, "bdogb", RegexOptions.IgnoreCase)
&&
Regex.IsMatch(s, "bvetb", RegexOptions.IgnoreCase)
)
{
...
}
Permutations don't scale, of course.
b's are optional.
Even with b's, dog won't match. This is probably a feature.
A full-blown word search feature would probably build an index.Anonymous
December 16, 2005
The comment has been removedAnonymous
June 07, 2009
PingBack from http://greenteafatburner.info/story.php?id=2319Anonymous
June 08, 2009
PingBack from http://quickdietsite.info/story.php?id=3660Anonymous
June 17, 2009
PingBack from http://pooltoysite.info/story.php?id=3315