Search code examples
rubyregexrubular

Removing parenthesis and digit from string with regex


I have strings that look like this:

Executive Producer (3)

Producer (0)

1st Assistant Camera (12)

I'd like to use a regex to match the first part of the string and to remove the " (num)" part (the space preceding the parentheses and the parenthesis/digit in the parentheses). After using the regex I'd want to have my vars equal to: "Executive Producer", "Producer", "1st Assistant Camera"

If you know any resources for learning regexes that would be great too.


Solution

  • You just have to select all the characters except the final parenthesis and their numeric content:

    (.+) \(\d+\)
    

    The first two parenthesis capture the content (here, all content, declared by the point). Then, you want two parenthesis (be careful to the slash), meaning we do not want these parenthesis to capture the "\d+" expression, which is a number.

    One of my favorite regex site: http://www.regular-expressions.info/