Reputation: 57469
I want to match only words from A-Z and a-z with an optional period at the end. This is the code I have so far:
return Regex.IsMatch(word, @"[A-Za-z]\.?")
This means the following should return true: test
, test.
.
The following should return false: t3st
, test..
, .
, .
Right now this regex returns true for everything.
Upvotes: 0
Views: 700
Reputation: 1129
Your regex only asks for a single letter followed by an optional period. Since all your words start with a letter, that regex returns true.
Notice the + in Prince John Wesley's answer - that says to use one or more letters, so it'll "eat" all the letters in the word, stopping at a non-letter. Then the \.? tests for an optional period.
I don't think the ^ and $ are needed in this case.
You might also want to include the hyphen and the single-quote in your regex; otherwise you'll have problems with hyphenated words and contractions.
That may get messy; some words have more than one hyphen: "port-of-call" or "coat-of-arms", for example. Very rarely you'll find a word with more than one quote: "I'd've" for "I would have". They're rare enough you can probably forget about 'em. (oops! there's a word that starts with a quote... :)
Upvotes: 0
Reputation: 63698
Try this regex
:
@"^[A-Za-z]+\.?$"
Boundary matchers
Greedy quantifier
Upvotes: 4