Search code examples
regexactionscript

string before dynamic text regexp, return repetitive array result


I'm trying to get some string before '_', I managed to do that using regexp and make it dynamically, but somehow it returns in array form with 2 repeat answer. I know I could just get like array[0] and pass it over, but it doesn't looks straightforward. What have I done wrong?

function stringBefore($string:String, $before:String):void {
        var s:String = $string;         
        var start:RegExp = /^([^/;
        var end:RegExp = /]*)/g;
        var completeRegExp:RegExp = new RegExp(start.source + $before + end.source);

        trace(s.match(completeRegExp))
    }

Exp: Passing something like 'SFX_SOUND' I will get [SFX, SFX] in an array


Solution

  • You cannot combine regexes that way. You can only combine string patterns and then compile a regex object. So, you might want to fix your code like this:

    var start:RegExp = "^([^";
    var end:RegExp = "]*)";
    var completeRegExp:RegExp = new RegExp(start.source + $before + end.source, "g");
    

    Or, maybe just using strings

    var start:String = "^([^";
    var end:String = "]*)";
    var completeRegExp:RegExp = new RegExp(start + $before + end, "g");