Reputation: 2063
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
Reputation: 1402
As simple as that: ^\w+(\.[gl]t){0,1}$
. \w
will match any string before .gt
or .lt
Upvotes: 1
Reputation: 31011
You can use:
^[^.\n]+(\.(gt|lt))?$
Key differences to your solution:
.
I used [^.\n]
- any character
other than a dot or a newline.+
, to accept only non-empty content.(?<!\..*)
) and the preceding |
.?
, because the .lt
or .gt
suffix is optional.One more remark: In negative lookbehind you can not use quantifiers
(you tried .*
).
Upvotes: 2
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:
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 lineUpvotes: 2