1

The regex pattern I tried to use is "\$\{(\b[0-9]+\b)\}(-r\{(.)+\})?(-i\[((\b[0-9]+\b)?:?(\b[0-9]+\b)?)?\])?"

Let me break it down:

  1. I want a decimal number enclosed in ${} which is captured by the first group. This group is mandatory.

  2. -r{} is the second group. Within those braces I want to able to accept a regex pattern string. (hence the "-r{[a-zA-Z]}" in the test string) So I just put (.)+ to accept any character. And this group (-r{}) is optional.

  3. -i group can accept strings like "-i[2]" or "-i[1:2]" or "-i[:2]" or "-i[1:]". And the -i group is optional.

The test works and captures the groups perfectly when there's one string. So I expected to catch multiple matches with similar group of strings separated by space. My test string is "${1}-r{[a-zA-Z]}-i[1:2] ${2}-r{[0-9]}-i[:88]". I wanted "${1}-r{[a-zA-Z]}-i[1:2]" and "${2}-r{[0-9]}-i[:88]" to be separate matches. When I tried it in regex101, it returned as 1 single match and captured "-r{[a-zA-Z]}-i[1:2] ${1}-r{[a-zA-Z]}" as group 2. Link to regex101. When I tried debugging it, I found that when it encountered the (.)+ part, it started parsing from the end of the string. So, I guess that's a mistake if I want to extract multiple matches. What should I do?

Can you even capture a regex pattern enclosed within a string with regex?

  • You must have meant `\$\{([0-9]+)\}(-r\{[^{}]*})?(-i\[(([0-9]+)?:?([0-9]+)?)?\])?` ([demo](https://regex101.com/r/YjfIiP/2)). Note you need no word boundaries here, they are all implicit at those locations. – Wiktor Stribiżew Mar 15 '21 at 18:03
  • So, there are two very common issues: 1) you need to remove anchors, 2) use lazy matching/negated character class. – Wiktor Stribiżew Mar 15 '21 at 18:09
  • Thanks. You're a life saver. So lazy matching doesn't cause the parser to parse from the end of the string like .+ did? – Kalid Ahamed Mar 15 '21 at 18:21
  • `.+` is too greedy meaning it matches all up to the string end, and then the regex engine tries to accommodate the subsequent patterns match by stepping back from the end of the string. – Wiktor Stribiżew Mar 15 '21 at 18:25

0 Answers0