Ahmed
Ahmed

Reputation: 11413

Conforming a Regex that matches the following patterns?

I have the following patterns in a URL.

  1. John.Smith
  2. John.Smith.1
  3. John.Al-Smith
  4. John.al-smith.1
  5. John.Smith.Al-Caboon

Where the first (.) is mandatory and with at least one character before and after the first (.), the rest of the stuff (the numbers, hyphen, and the second (.)) are optional.
I created the following Regex:

^\w+.\w+-*\w*.?\d*\w*-*\w*

Though it successfully matched all the above patterns, it also matches some undesired patterns like:

  1. "login" (Without the mandatory first dot)
  2. "users/john" (with an undesired / and also without the mandatory first dot)
  3. "1234" (Invalid, the pattern has to start by a character)

What am I doing wrong here?

Upvotes: 0

Views: 348

Answers (5)

Jaskirat
Jaskirat

Reputation: 1094

Problems observed with your regex

  1. "." is a meta character in regex. It matches "anything". You should escape it to match the dot. Like this: \.
  2. \w is a character class which includes small letters, caps, numbers and underscore. This explains why "1234" passed.

Try this

^[a-zA-Z]\w*(\.[-\w]+){1,2}$

Upvotes: 2

user184968
user184968

Reputation:

And \w means [A-Za-z0-9_]. Which is why it matches "1234".

Upvotes: 0

BigAl
BigAl

Reputation: 23

[a-zA-Z]\w*(.[-\w]+){1,2}$ works well...Check it out at http://regexr.com?3020g

Upvotes: 0

Rubens Farias
Rubens Farias

Reputation: 57996

Use this expression: \w+\S*?\.\w+\S*

I read your definition as:

  • at least one character
  • mandatory dot
  • at least one character

This ran successfully using .NET RegexOptions.ECMAScript and RegexOptions.Multiline

Upvotes: 0

catwalk
catwalk

Reputation: 6476

maybe you should escape the dots

\.

Upvotes: 1

Related Questions