3

我有一个这样的字符串:

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

我想获取所有包含数字2 的组字符串总是由 3 个数字组成的组,它们之间有一个破折号。

所以我的正则表达式会返回这个:

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

我试过这个没有成功::\d*2-|-2-|2-\d*:

谢谢你的帮助。

4

4 回答 4

5

你可以试试这个正则表达式

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

[^:]表示匹配任何字符,除了:

[^:]*将匹配 0 到多个字符,除了:

2(?=[-:])仅当它后跟-or时才匹配 2:

(?<=[-:])2将匹配 2 只有它前面是-or:

或者

[^:]*\b2\b[^:]*
于 2013-06-06T12:29:32.620 回答
0

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.

于 2013-06-06T12:31:30.847 回答
0

You can use this:

(?<=:)(?:2-\d+-\d+|(?:\d+-){1,2}2\b[^:]*)
于 2013-06-06T12:32:02.347 回答
0

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

于 2013-06-06T12:33:02.053 回答