eKeR
eKeR

Reputation: 65

Capturing a Repeated Group with reference

I tried to find the digits (less the first) with this expression, but it works only with the last digit... I know that need capturing a repeat group and not repeating a captured group but I dont understand how is it.

reg:

(\d*)[a-zA-Z]+\d+(?:\.(\d*))*\.[a-zA-Z]+

example

1212asdfasdfdasf101.102.103.asdsadasdasd

1213asdfasdfdasf104.105.106.asdsadasdasd

I want capture 102 and 103, 105, 106, but 1212 and 1213 too. How?? Thanks!

Upvotes: 2

Views: 162

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

The answer depends on which language you're using.

For most flavours of regex,there is no "simple" answer... For instance, you might think you could do something like this:

^(?:.*?(\d+))+

...Which would (you'd hope) create a new capture group for each group of digits.

However, if you have a quick look at (for example) the java documentation, then you'll see it says:

Capturing groups are numbered by counting their opening parentheses from left to right

i.e. There is a fixed number, as specified by how many pairs of brackets you typed! Thus, in most languages, you'll need to do more than a simple regex match in order to do this job.

That is, unless you can make your regex less generalised (and much more ugly), by doing something horrible like:

^(?:.*?(\d+))?(?:.*?(\d+))?(?:.*?(\d+))?(?:.*?(\d+))?

You can, however, perform this regex match properly, using .NET or Perl 6.

Upvotes: 2

Related Questions