Reputation: 106
I have this sample string 111:222:333
. From this, I need to extract all three :
separated numbers. The output should find three matches - 111
and 222
and 333
.
I use this regex to achieve this: (?<=^|:)(\d+)(?=:|$)
.
However, I need this regex to match only when there are at least 2 matches. Hence, 111
should not match, but 111,222,...
should.
I cannot use standard split functions in Java, because my use case mandates the regular expression being dynamically read from the database.
How do I enforce 'at least two matches' condition?
Upvotes: 1
Views: 194
Reputation: 626794
You may use
(?<=\G(?!^):|^(?=\d+(?::\d+)+$))\d+
See the regex demo
Details
(?<=\G(?!^):|^(?=\d+(?::\d+)+$))
- a positive lookbehind that matches either of the two alternative locations in string:
\G(?!^):
- a position after a previous successful match and :
|
- or ^(?=\d+(?::\d+)+$))
- start of a string that is followed with 1+ digits and then 1 or more sequences of :
and 1+ digits up to the string end\d+
- consuming 1 or more digitsUpvotes: 1