Question

I'm trying to extract the first user-right from semicolon separated string which matches a pattern.

Users rights are stored in format: LAA;LA_1;LA_2;LE_3;

String is empty if user does not have any rights.

My best solution so far is to use the following regex in regex.replace statement: .*?;(LA_[^;]*)?.*

(The question mark at the end of group is for the purpose of matching the whole line in case user has not the right and replace it with empty string to signal that she doesn't have it.)

However, it doesn't work correctly in case the searched right is in the first position: LA_1;LA_2;LE_3;

It is easy to fix it by just adding a semicolon at the beginning of line before regex replace but my question is, why doesn't the following regex match it?

.*?(?:(?:^|;)(LA_[^;]*))?.*

I have tried numerous other regular expressions to find the solution but so far without success.

Was it helpful?

Solution

I am not sure I get your question right, but in regards to the regular expressions you are using, you are overcomplicating them for no clear reason (at least not to me). You might want something like:

function getFirstRight(rights) {
  var m = rights.match(/(^|;)(LA_[^;]*)/)
  return m ? m[2] : "";
}

OTHER TIPS

You could just split the string first:

function getFirstRight(rights)
{
    return rights.split(";",1)[0] || "";
}

To answer the specific question "why doesn't the following regex match it?", one problem is the mix of this at the beginning:

.*?

eventually followed by:

^|;

Which might be like saying, skip over any extra characters until you reach either the start or a semicolon. But you can't skip over anything and then later arrive at the start (unless it involves newlines in a multiline string).

Something like this works:

.*?(\bLA_[^;]).*

Meaning, skip over characters until a word boundary followed by "LA_".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top