-3

I am trying to create a regular expression that starts with a number but then matches de or ba followed by 3 to digits right after it. What it should match is:

1Ghde345c

22Zui2ba777@

What I have so far is:

/^[0-9]?(be|de)*\d{3,5}/gm

But it doesn't seem to work. Is there something I am missing?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

0

The provided regular expression currently requires that (be|de) immediately follow [0-9] at the beginning of the string:

^[0-9]?(be|de)*\d{3,5}

Based on the provided test strings, you instead want to match (be|de) followed by 3-5 digits at any position in the string, regardless of whether it immediately follows the digit at the start of the string. One way to achieve this is with the following regular expression:

^[0-9].*(be|de)\d{3,5}

  • ^[0-9].* is used instead of ^[0-9]? for two reasons:
    1. [0-9] is now a requirement instead of optional.
    2. .* matches any character zero or more times, following the initial [0-9].
  • (be|de)* has been replaced with (be|de) to enforce only a single match, but can be reverted if sequential matches of be or de are allowed.

Example using regex101

Andre Nasri
  • 237
  • 1
  • 6