-1

I have a series of numbers: [1, 4, 8, 16]

I need to determine if a number matches any of those.

My regex now is:

(1|4|8|16)

This matches the 1, 4, or 8 fine but, for the 16, it stops after the 1.

If I use (16) it will detect the 16 correctly but, obviously, not work to detect anything else.

My question is why the 16 in the first regex pattern stops detection after the 1 but the second pattern matches the full number.

Also, how to create a pattern that will match any of the digits to one in the collection correctly, regardless of how many digits they may be. i.e. 2, 3, 4+ not just 1 and/or 2, such that I could check within a collection as such [1, 64, 128, 1024] and match any number.

UPDATE

Also, I need to be able to extract the entire value in a capture group not just detect presence.

Update

The problem seems to be that the 1 in the 16 is matching the 1 and not proceeding to check the next letter before declaring a match with the single 1 option.

overcoded
  • 1,559
  • 13
  • 28

1 Answers1

1

why the 16 in the first regex pattern stops detection after the 1 but the second pattern matches the full number?

Because (1|4|8|16) that matches the 1 of 16 by 1| then regex-engine stops searching. Try (16|4|8|1) to matches both 1 and 16

How to create a pattern that will match any of the digits to one in the collection?

Try this regex: [0-9]+ or \d+

OR in a capture group: ([0-9]+) or (\d+)

See example https://regex101.com/r/40jdiq/1 and https://regex101.com/r/40jdiq/2

Heo
  • 201
  • 1
  • 10
  • Is simply re-ordering the numbers to start from those longest in length the defacto approach? Re: a blanket digital match - my use-case has restrictions on which digits can be matched. – overcoded Nov 21 '20 at 19:09