Regex to detect period at end of string, but not '...'

5.9k views Asked by At

Using a regex, how can I match strings that end with exactly one . as:

  • This is a string.

but not those that end with more than one . as:

  • This is a string...

I have a regex that detects a single .:

/[\.]{1}\z/

but I do not want it to match strings that end in ....

3

There are 3 answers

1
aidan On BEST ANSWER

What you want is a 'negative lookbehind' assertion:

(?<!\.)\.\z

This looks for a period at the end of a string that isn't preceded by a period. The other answers won't match the following string: "."

Also, you may need to look out for unicode ellipsis characters… You can detect this like so: str =~ /\u{2026}/

5
Dekel On

You can use:

[^\.][\.]\z

You are looking for a string that before the last dot there is a char that is not a dot.

2
Taylor Brockman On

I like Regexr a lot!

Solution similar to Dekel:

[^.]+[.]

Live demo