REGEX to get Nth word between two characters

Viewed 69

I am trying to get a regex to use in Data Studio, what I am trying to do is be able to pull out the following into custom fields so I would need 4 regex's for each one

STRING = first_Product (21) » second_Product_3 (64) » third_Product (53) » fourth_Product_4 (21)

into.

custom_field_1 = first_product.

custom_field_2 = second_product.

custom_field_3 = third_product.

custom_field_4 = fourth_product.

To get the first I am using

.+?(?=\()

To get the second one I am able to use

    \»(.*?)\( 

Would anyone be able to helo with this

1 Answers

You could use a regex with a quantifier like {2} {3} to get the specific matches from capture group 1.

^(?:(?:^|»\s+)(.*?)\s*\(\d+\)(?:\s+|$)){2}

The pattern matches:

  • ^ Start of string
  • (?: Non capture group to match as a whole part
    • (?:^|»\s+) Assert the start of the string or match » and 1+ whitespace chars
    • (.*?) Capture group 1, match 1+ times any char as least as possible
    • \s*\(\d+\) Match optional whitespce chars and 1+ digits between parenthesis
    • (?:\s+|$) Match either 1+ whitespace chars or assert the end of the string
  • ){2} Close the non capture group and repeat n times (in this example 2 times)

Regex demo

Related