stefanobaldo
stefanobaldo

Reputation: 2063

Do not match if there is more than one of a single character

I need to create a regex that validates any text with no dots or any text ending with .gt or .lt. Any text with more that one dot should also be invalid.

anytext // valid
anytext.gt // valid
anytext.lt // valid
anytext.xx // invalid
anytext.xx.gt // invalid

I've created this: ^.*(\.(gt|lt)|(?<!\..*))$

It works well except by the fact that it accepts more than 1 dot, so something like foo.bar.gt is being validated and should not.

Upvotes: 2

Views: 82

Answers (4)

Yati Sawhney
Yati Sawhney

Reputation: 1402

As simple as that: ^\w+(\.[gl]t){0,1}$. \w will match any string before .gt or .lt

Upvotes: 1

David Faber
David Faber

Reputation: 12495

I think this is straightforward:

^[^.]+(\.[gl]t)?$

See Regex101 demo here.

Upvotes: 1

Valdi_Bo
Valdi_Bo

Reputation: 31011

You can use:

^[^.\n]+(\.(gt|lt))?$

Key differences to your solution:

  • Instead of the "initial" . I used [^.\n] - any character other than a dot or a newline.
  • As a quantifier following it I used +, to accept only non-empty content.
  • I dropped the second alternative ((?<!\..*)) and the preceding |.
  • After the capturing group I added ?, because the .lt or .gt suffix is optional.

One more remark: In negative lookbehind you can not use quantifiers (you tried .*).

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163632

You could match one or more word characters \w+ or specify in a character class what you want to match and end with an optional dot followed by gt or lt:

^\w+(?:\.[gl]t)?$

Explanation

  • ^ Assert position at the start of the line
  • \w+ One or more word characters
  • (?: Non capturing group
    • \.[gl]t Match a dot and either g or l followed by t
  • )? Close non capturing group and make it optional
  • $ Assert position at the end of the line

Upvotes: 2

Related Questions