0

I have used Regex in C#. How do I use this type of Regex in Javasript. This type of regex works in C#.

I have the following Regex:

(?<Month>[A-Za-z]{3}) (?<Date>[0-9]{2}) (?<Hour>[0-9]{2}):(?<Minutes>[0-9]{2}):(?<Seconds>[0-9]{2}) (?<ComputerName>[A-Za-z0-9\-\ ]+): (?<KernalTime>[0-9\.\[\]\ ]+) (?<Message>[A-Za-z\(\)\.\ ]+)

to Parse the Following Line (All Lines are similar):

Nov 24 14:24:31 Dell-Inspiron-N5110 kernel: [    0.000000]   Intel GenuineIntel

In javascript i used the following code.

matchRegexParse: function () {



   var myString = "Nov 24 14:24:31 Dell-Inspiron-N5110 kernel: [    0.000000]   Intel GenuineIntel";
    var myRegexp = new RegExp(
        "(?<Month>[A-Za-z]{3}) (?<Date>[0-9]{2}) (?<Hour>[0-9]{2}):(?<Minutes>[0-9]{2}):(?<Seconds>[0-9]{2}) (?<ComputerName>[A-Za-z0-9\-\ ]+): (?<KernalTime>[0-9\.\[\]\ ]+) (?<Message>[A-Za-z0-9\(\)\.\ \-\:]+)",
        "gi");

    var match = myRegexp.exec(myString);
    alert(match);
},

I get the following Error (See Attached Image):

enter image description here

EDIT (ERROR AS TEXT):

Uncaught SyntaxError: Invalid regular expression: /(?<Month>[A-Za-z]{3}) (?<Date>[0-9]{2}) (?<Hour>[0-9]{2}):(?<Minutes>[0-9]{2}):(?<Seconds>[0-9]{2}) (?<ComputerName>[A-Za-z0-9\-\ ]+): (?<KernalTime>[0-9.\[\]\ ]+) (?<Message>[A-Za-z0-9\(\)\.\ \-\:]+)/: Invalid group

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119
  • To start with you should use a regex literal to avoid the escaping (that you forget). See https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions – Denys Séguret Nov 25 '13 at 18:36

1 Answers1

2

As far as I'm aware JavaScript does not support named groups:

Named capturing groups in JavaScript regex?

You can either convert to numeric-index groups by removing the <Angle-Bracket-Parts>

var re = /([A-Za-z]{3}) ([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) ([A-Za-z0-9\-\ ]+): ([0-9\.\[\]\ ]+) ([A-Za-z0-9\(\)\.\ \-\:]+)/gi

Which will mean that you can only access the captured information by numeric offsets:

var match = re.exec(myString);
console.log( match[1] ) // Nov 24

or use something like:

http://xregexp.com/

Community
  • 1
  • 1
Pebbl
  • 34,937
  • 6
  • 62
  • 64