Search code examples
regexcharacter-class

regex number OR period


I am having a problem with a regex. I am trying to find the combination of a Letter and digit/period/hyphen. So it will always start with a capital letter, followed by either a digit, period or hyphen, followed by a space. So all of these should work

  • D7
  • A.
  • H-

But these shouldn't

  • GJ
  • G6. (No space after the second param)

At the moment I am trying this without success

[A-Z]{1}\d{1}|\.\s

Solution

  • You need a character class:

    (?<= |^)[A-Z][\d.-](?= |$)
    

    See demo

    Minor FYI: A hyphen at the start or end of a character class is a literal hyphen (not a range).

    Other minor FYI: The quantifier {1} is redundant/implied - it makes no difference if you add it, so don't (regex is hard enough to read already).