Search code examples
regexactionscript-3actionscript

How to only select the lookahead matches


i have found a pretty good regEx but I have difficulty excluding part of the match.

What I want is select parentheses, but ONLY if there's 1 number (multiple digits) between the start and end parentheses or a single character or if its empty between them (). If theres some character in front of the () it should not select it. I'm using it to replace some part of a string therefore I want to only match the parentheses since I want to remove them. The current regExp matches the parentheses and the part inside them.

.(?<=[^a-z]\()([\d]*|[a-zA-Z])(?=\)).

(x+2)/(x)   -> only select ( ) in (x) 
-(2)+.      -> only select ( ) in (2)
(wsd).      -> select nothing
(x)^2+2     -> only select ( ) in (x)
sin(x).     -> select nothing
(22313)a.   -> only select ( ) in (22313)
+23-3()/(3x)+(x).  -> only select () in () and ( ) in (x)
sin(x)+3*x^2+(x)+23 -> only select ( ) in (x)

Any idea how to NOT-select the part between the parentheses?

I have set up a regexp tester: https://regex101.com/r/fYDm2L/1


Solution

  • Don't try to match parenthesis one at a time, describe the whole substring and use capture groups you can refer to in the replacement string:

    var result:String = str.replace(/ (^|[^a-z]) \( (\d*|[a-z]) \) /gix, "$1$2");
    

    demo