Generally speaking, to accomplish something like this, you have at least 3 options:
- Use lookarounds, so you can match precisely what you want to capture
- No lookbehind in Javascript, unfortunately
- Use capturing group to capture specific strings
- Near universally supported in all flavors
- If all else fails, you can always just take a
substring
of the match
- Works well if the length of the prefix/suffix to chop is a known constant
References
Examples
Given this test string:
i have 35 dogs, 16 cats and 10 elephants
These are the matches of some regex patterns:
You can also do multiple captures, for example:
(\d+) (cats|dogs)
yields 2 match results (see on rubular.com)
- Result 1:
35 dogs
- Group 1 captures
35
- Group 2 captures
dogs
- Result 2:
16 cats
- Group 1 captures
16
- Group 2 captures
cats