Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Variable in Regular Expression in javascript

Using regular expression match this pattern - 5h to 6h,4am to 9am,3pm to 8pm,4h to 9pm......

and I have already regular expression for - 5h, 4pm, 5am......

and I want to use this regular expression for match 4am to 9am.

like var reg_expr = (/(\d{1,2}?h$)|(\d{1,2}h(?=\s+))|(\d{1,2}:\d{2}([ap]m)?$)|(\d{1,2}:\d{2}([ap]m)(?=\s+))|(\d{1,2}:\d{2}(?=\s+))|(\d{1,2}([ap]m)?$)|(\d{1,2}([ap]m)(?=\s+))/gi)

this reg_expr matches pattern like 4h,5pm,8am.....

and this variable uses in match 4am to 9am,

like var reg_data = ((reg_expr)(/\s(to)(?=\s)/gi)(reg_expr))...

Is it possible.??? if yes then how???

like image 672
Bhumi Patel Avatar asked Feb 23 '26 11:02

Bhumi Patel


2 Answers

Is it possible.???

Yes

if yes then how???

You can get the string representation of a RegExp object by calling the #toString method or using the source property.

Moreover, you can create a RegExp object from a string.

var reg_expr = /(\d{1,2}?h$)|(\d{1,2}h(?=\s+))|(\d{1,2}:\d{2}([ap]m)?$)|(\d{1,2}:\d{2}([ap]m)(?=\s+))|(\d{1,2}:\d{2}(?=\s+))|(\d{1,2}([ap]m)?$)|(\d{1,2}([ap]m)(?=\s+))/;

var reg_data = new RegExp(
    reg_expr.source + 
    /\s(to)(?=\s)/.source +
    reg_expr.source,
    'gi'
);

alert(reg_data.source);
like image 187
Stephan Avatar answered Feb 26 '26 00:02

Stephan


If your regex is complex and becomes unreadable at some point, you might consider the grammar approach. A grammar can be declared as an object, with symbols as keys and corresponding productions as values. Productions are actually just regexes, but with special syntax for symbols (like @symbol) and whitespace for readability. When you need a regex for a symbol, you (trivially) create it on the fly:

// grammar for time intervals

times = {
    'space'   : '\\s+',
    'digit'   : '\\d',
    'hours'   : '@digit @digit?',
    'minutes' : ': @digit @digit',
    'suffix'  : 'h | am | pm',
    'time'    : '@hours @minutes? @suffix?',
    'interval': '@time @space to @space @time'
};

// convert a grammar rule to regex

function regex(grammar, symbol, flags) {

    function expand(s) {
        return s.replace(/@(\w+)/g, function(_, $1) {
            return '(?:' + expand(grammar[$1]) + ')';
        });
    }

    return new RegExp(
        expand(grammar[symbol]).replace(/\s+/g, ''),
        flags);
}

// test!

interval = regex(times, 'interval', 'g');
test = '5h to 6h,4am to 9am,3pm to 8pm,4h to 9pm';
document.write(test.match(interval).join(' ; '));
like image 45
georg Avatar answered Feb 26 '26 00:02

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!