mimipc
mimipc

Reputation: 1374

Regex - Find all groups where you can find a given number

I have a string such as this one :

:1-2-35:2-3-1:5-6-27456:35-2-11:9-5-6:1-5-2:

I'd like to get all the groups containing number 2 The string is always composed of groups of 3 numbers with a dash between them.

So my regex would return this :

1 => :1-2-35:
2 => :2-3-1:
3 => :35-2-11:
4 => :1-5-2:

I've tried this with no success : :\d*2-|-2-|2-\d*:

Thanks for your help.

Upvotes: 3

Views: 64

Answers (4)

Anirudha
Anirudha

Reputation: 32797

You can try this regex

[^:]*(?<=[-:])2(?=[-:])[^:]*

[^:] means match any character except :

[^:]* would match 0 to many characters except :

2(?=[-:]) would match 2 only if it is followed by - or :

(?<=[-:])2 would match 2 only it is preceded by - or :

OR

[^:]*\b2\b[^:]*

Upvotes: 5

gkalpak
gkalpak

Reputation: 48211

If the groups will always contain 3 number (and 2 dashes), you can use a regex like this:

:(2-\d+-\d+|\d+-2-\d+|\d+-\d+-2)(?=:)

(Note, it may vary slightly, based on the regex implementation of the language you are using.)

See, also, this short demo in PHP.

Upvotes: 0

Bob Vale
Bob Vale

Reputation: 18474

The following regex should do the job

(?<=:)(?:2-\d+-\d+)|(?:\d+-2-\d+)|(?:\d+-\d+-2)(?=:)

The only limitation is whilst it filters on the : chars they are not included in the match. If you try and include the : chars in the match then sequential matches will fail because the trailing : will already be gone for the beginning of the next match

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can use this:

(?<=:)(?:2-\d+-\d+|(?:\d+-){1,2}2\b[^:]*)

Upvotes: 0

Related Questions