Home > other >  Regex for specific strings or just numbers
Regex for specific strings or just numbers

Time:05-31

I have a strange use case Numeric Input needs the ability to either have specific strings (e.g. 'cat', 'dog') and/or just numbers. I need to create a regex that accepts only the specified strings as the prefix or suffix of the entered text.

E.g.

  • cat1
  • 1cat
  • cat
  • 1

Should all be accepted.

I currently have this:

<input #input inputmode="numeric" pattern="cat\/(. ?)\/?(?:cat|$)"/>

But I am not achieving the desired outcome.

Are there any best practice ways of achieving this?

CodePudding user response:

I would an alternation for this to keep things simple:

^(?:\d cat|cat\d |cat|\d )$

This pattern says to match:

^(?:
    \d cat  a digit followed by "cat"
    cat\d   "cat" followed by a digit
    cat     "cat" by itself
    \d      any number by itself
)$

Demo

  • Related