The Problem is Not Greediness, but Case-Sensitivity
Currently your regex matches the 12
at the end of serialnun12
, probably because it is case-sensitive. We have two options: using upper-case, or making the pattern case-insensitive.
Option 1: Use Upper-Case
If you only want 123456
, you can use:
SERIALNO\K\d+
The \K
tells the engine to drop what was matched so far from the final match it returns.
If you want to match the whole string and capture 123456
to Group 1, use:
.*?SERIAL\D+(\d+).*
Option 2: Turning Case-Sensitivity On using (?i)
inline or the i
flag
To only match 123456
, you can use:
(?i)serial\D+\K\d+
Note that if you use the g
flag, this would match both numbers.
If you want to match the whole string and capture 123456
to Group 1, use:
(?i).*?serial\D+(\d+).*
A few tips
- You can turn case-insensitivity either with the
(?i)
inline modifier or the i
flag at the end of the pattern: /serial\D+\K\d+/i
- Instead of
[^\d]
, use \D
- There is no need for a lazy quantifier in something like
\D+\d+
because the two tokens are mutually exclusive: there is no danger that the \D
will run over the \d