2

I'm trying to write a regex similar to

^[a-zA-Z.{0,1},{0,1}'{0,1}]*

However, this can accept more than one comma, period, and apostrophes.

For example "String.,'" is allowed but "str.,..,,,'''" should not be allowed.

  • 1
    Does this answer your question? [Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters](https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a) – AaronJ Aug 23 '21 at 20:03

1 Answers1

1

Use

^(?!.*([.,']).*\1)[a-zA-Z.,']*$

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    (                        group and capture to \1:
--------------------------------------------------------------------------------
      [.,']                    any character of: '.', ',', '''
--------------------------------------------------------------------------------
    )                        end of \1
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    \1                       what was matched by capture \1
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  [a-zA-Z.,']*             any character of: 'a' to 'z', 'A' to 'Z',
                           '.', ',', ''' (0 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37