Yes, you can use a regex to match strings containing "else" very easily. The expression is very simple:
\belse\b
The \b
at either end of the expression indicates a "word boundary", which means that the expression will only match the whole word else
and will not match when else
is part of another word. Note however that word boundaries don't continue on into punctuation characters, which is useful if you're parsing sentences as you are here.
Hence the expression \belse\b
will match these sentences:
- Blah blah else blah
- else blah blah blah
- blah blah blah else
- blah blah blah else.
// note the full stop
...but not this one...
You don't say which language you're coding in, but here's a quick example in C#, using the System.Text.RegularExpressions.Regex class and written as an NUnit test:
[Test]
public void regexTest()
{
// This test passes
String test1 = "This is a sentence which contains the word else";
String test2 = "This is a sentence which does not";
String test3 = "Blah blah else blah blah";
String test4 = "This is a sentence which contains the word else.";
Regex regex = new Regex("\\belse\\b");
Assert.True(regex.IsMatch(test1));
Assert.False(regex.IsMatch(test2));
Assert.True(regex.IsMatch(test3));
Assert.True(regex.IsMatch(test4));
}