2

I have the following input string:

  02:00:00_03:00:00_1234@someemail.or.domain.com

or this :

  02:00:00_03:00:00_mtwrf_1234@someemail.or.domain.com 

I'm trying to write a javascript regex that will match both. The "mtwrf" is optional... it may or may not be present in the input.

I've been using this site to test: http://www.regexpal.com/

This pattern:

  (\d\d\:\d\d:\d\d\_){2}([mtwrfsn\_]*)([\w\d]+\@?[\w\d\.]+)

seems to work as per the regexpal.com website using the input string:

  02:00:00_03:00:00_mtw_1234@test.domain.com

But ... when I plug that into my code... it's not matching / finding the "02:00:00".

Here's my javascript code:

       var pattern  = /(\d\d\:\d\d:\d\d\_){2}([mtwrfsn\_]*)([\w\d]+\@?[\w\d\.]+)/;
            if (rules_array[i].length > 0) {
                    searchval = rules_array[i].match(pattern);
            }
            console.log(searchval);

And the output I get is this:

[ '02:00:00_03:00:00_1234@test.domain.com',
  '03:00:00_',
  '',
  '1234@test.domain.com',
  index: 0,
  input: '02:00:00_03:00:00_1234@test.domain.com' ]

I think i should be seeing something like this instead:

[ '02:00:00_03:00:00_1234@test.domain.com',
  '02:00:00_',
  '03:00:00_',
  '1234@test.domain.com',
  index: 0,
  input: '02:00:00_03:00:00_1234@test.domain.com' ]

Can you see where my bug / problem is? Thanks.

Happydevdays
  • 1,982
  • 5
  • 31
  • 57

1 Answers1

0

The problem you encountered is related to repeated capturing groups, see How to capture an arbitrary number of groups in JavaScript Regexp?.

However, the solution for your case is to just spell out the capturing group for the second time value:

var pattern  = /(\d\d\:\d\d:\d\d_)(\d\d\:\d\d:\d\d_)([mtwrfsn_]*)(\w+?[\w.]+)/;
var searchval = "02:00:00_03:00:00_mtw_1234@test.domain.com".match(pattern);
console.log(searchval);

yielding

[
  "02:00:00_03:00:00_mtw_1234",
  "02:00:00_",
  "03:00:00_",
  "mtw_",
  "1234"
]

The pattern may be further shortened, just note that [\w\d] = \w since \w matches digits as well as \d.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563