2

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.

revo
  • 47,783
  • 14
  • 74
  • 117
stefanobaldo
  • 1,957
  • 6
  • 27
  • 40

4 Answers4

2

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
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

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

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • Are you sure your remark is correct? [`Why can't you use repetition quantifiers in zero-width look behind assertions `](https://stackoverflow.com/questions/23964362/why-cant-you-use-repetition-quantifiers-in-zero-width-look-behind-assertions/24591663) – The fourth bird Apr 13 '18 at 19:03
  • His remark is correct about *lookbehind*, yes - assuming we're talking about Java or PCRE (but not .Net) – David Faber Apr 14 '18 at 14:31
1

I think this is straightforward:

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

See Regex101 demo here.

David Faber
  • 12,277
  • 2
  • 29
  • 40
  • 1
    You'll probably want to do `^[^.]+?(\.[gl]t)?$` (greedy), otherwise it could capture two lines instead of one. – l'L'l Apr 13 '18 at 18:24
  • The OP did say "any text" ;-) – David Faber Apr 13 '18 at 18:36
  • 1
    It's doubtful line-feeds are considered "text". In fact you only should need to do `^([^.]+\.[gl]t)$`, which would be 24 steps less than your current solution. – l'L'l Apr 13 '18 at 18:39
1

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

Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19