Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match at every second occurrence

Tags:

regex

Is there a way to specify a regular expression to match every 2nd occurrence of a pattern in a string?

Examples

  • searching for a against string abcdabcd should find one occurrence at position 5
  • searching for ab against string abcdabcd should find one occurrence at position 5
  • searching for dab against string abcdabcd should find no occurrences
  • searching for a against string aaaa should find two occurrences at positions 2 and 4
like image 929
Shyam Avatar asked Feb 26 '09 08:02

Shyam


People also ask

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.

What is a capture group regex?

Advertisements. Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What method should you use when you want to get all sequences matching a regex pattern in a string?

To find all the matching strings, use String's scan method.

How do you match a string in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.


2 Answers

Use grouping.

foo.*?(foo) 
like image 171
Alex Barrett Avatar answered Sep 21 '22 15:09

Alex Barrett


Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.

You would construct the following regex:

abc+d.*?(abc+d) 

This would match strings of the form: <your-pattern>...<your-pattern>. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.

like image 21
Il-Bhima Avatar answered Sep 19 '22 15:09

Il-Bhima