rubyregexstringoniguruma

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


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

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

I have a regex that detects a single .:

/[\.]{1}\z/

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


Solution

  • 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}/