0

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.

1
  • you want digits too? try: @"^[A-Za-z0-9]\.?$" Commented Oct 30, 2011 at 1:27

2 Answers 2

4

Try this regex:

@"^[A-Za-z]+\.?$"

Boundary matchers

  • ^ means beginning of a line
  • $ means end of a line

Greedy quantifier

  • [A-Za-z]+ means [A-Za-z], one or more times
Sign up to request clarification or add additional context in comments.

Comments

0

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... :)

1 Comment

Without the ^ and $, the regex would still return true for anything containing a letter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.