Monica
Monica

Reputation: 35

regex matches dot but not at the end

I should write a regex for a filename, it has allowed chars

^[a-zA-Z0-9 ()+,._&-]+$

but it can't finish with a dot.

can I put the two together?

Upvotes: 1

Views: 62

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627517

You may use a negative look-ahead at the beginning:

^(?!.*\.$)[a-zA-Z0-9 ()+,._&-]+$
  ^^^^^^^

The (?!.*\.$) look-ahead will be "triggered" in the beginning of the input, and will fail the match once a literal dot is found at the end of the string.

See regex demo

Also, you can use another version with a negative-lookbehind (if the regex engine supports it). Here is a bad example of the look-behind based solution as it will perform lots of unnecessary backtracking:

^[a-zA-Z0-9 ()+,._&-]+(?<!\.)$

Here is a better one as it has a possessive quantifier that will eliminate unnecessary backtracking and will check for the period only at the end of the string:

^[a-zA-Z0-9 ()+,._&-]++(?<!\.)$
                     ^^

An alternative to the possessive quantifier is an atomic group:

^(?>[a-zA-Z0-9 ()+,._&-]+)(?<!\.)$
 ^^^                     ^

Upvotes: 3

Related Questions