I'm trying to find the following pattern:
(NUMBERS)(STRING)(NUMBERS)(STRING)(NUMBERS)(STRING)
with at least one group of (NUMBERS)(STRING) present. I also want to get in the match the number and the string separately.
Example:
1234abc234qwy2342nioo
23oin234noik32342noi
234nio234koi2341nio
The output I want is as follows:
However, if the input is just a number, I don't want it to match with the pattern.
I came up with the following regex:
^(\d*)([a-z]*)(\d*)([a-z]*)(\d*)([a-z]*)$
However, now it captures if I give it a number alone as well. For example, it matches the following patterns:
2342324
Is there a way I can impose on the regex that it captures at least one group of (NUMBERS)(STRINGS) and not match the numbers alone.
The problem is that you are using the *
, which means zero-or-more. In other words, if you use *
, it's essentially optional. +
means one-or-more, so that's more appropriate in your case. For instance:
^(\d+[a-z]+){1,3}$
Or, if you want to retain the capture groups:
^(?:(\d+)([a-z]+)){1,3}$
Or:
^(\d+)([a-z]+)(?:(\d+)([a-z]+))?(?:(\d+)([a-z]+))?$