0

I know there are a billion regex questions on stackoverflow, but I can't understand why my uri matcher isn't working in node.

I have the following:

var uri = "file:tmp.db?mode=ro"

function parseuri2db(uri){
    var regex = new RegExp("(?:file:)(.*)(?:\\?.*)");
    let dbname = uri.match(regex)
    return dbname
}

I'm trying to identify only the database name, which I expect to be:

  1. After an uncaptured file: group
  2. Before an optional ? + parameters to end of string.

While I'm using:

var regex1 = new RegExp("(?:file:)(.*)(?:\\?.*)");

I thought the answer was actually more like:

var regex2 = new RegExp("(?:file:)(.*)(?:\\??.*)");

With a 0 or 1 ? quantifier on the \\? literal. But the latter fails.

Anyway, my result is:

console.log(parseuri2db(conf.db_in.filename))

[ 'file:tmp.db?mode=ro',
  'tmp.db',
  index: 0,
  input: 'file:tmp.db?mode=ro' ]

Which seems to be capturing the whole string in the first argument, rather than just the single capture group I asked for.

My questions are:

  1. What am I doing wrong that I'm getting multiple captures?
  2. How can I rephrase this to capture my capture groups with names?

I expected something like the following to work for (2):

function parseuri2db(uri){
  // var regex = new RegExp("(?:file:)(.*)(?:\\?.*)");
  // let dbname = uri.match(regex)
  var regex = new RegExp("(?<protocol>file:)(?<fname>.*)(<params>\\?.*)");
  let [, protocol, fname, params] = uri.match(regex)
  return dbname
  }
  console.log(parseuri2db(conf.db_in.filename))

But:

  SyntaxError: Invalid regular expression: /(?<protocol>file:)(?<fname>.*)(<params>\?.*)/: Invalid group

Update 1

Answer to my first question is that I needed to not capture the ? literal in the second capture group:

"(?:file:)([^?]*)(?:\\??.*)"
Mittenchops
  • 18,633
  • 33
  • 128
  • 246

1 Answers1

0

That particular node regex library does not support groups.

Mittenchops
  • 18,633
  • 33
  • 128
  • 246