Search code examples
regexalternationregex-alternation

Regex alternation optional replace


I would like to make my life translating Objective-C to Swift easier; I'm currently writing a program that will match certain often-used constructions (such as methods, properties and variables) and replace them with the Swift version. Now I'm trying to replace the +/- in front of a method name optionally to either class if + or nothing if -.

I can't seem to find how I can make the alternation (\+|-) be replaced with either class or based on the choice. Is this possible in pure regex? Or do I need to put this in my application logic?

Edit: expected input and output:

- (void)composeView(...) gives func composeView(...)

+ (void)composeView(...) gives class func composeView(...)


Solution

  • You can use two regex, the first one can be:

    - \(\w+\)(composeView\(.*?\))
    

    Working demo

    Take a look at the Substitution section

    enter image description here

    And the second one:

    \+ \(\w+\)(composeView\(.*?\))
    

    Working demo

    enter image description here