WhiiteRussian WhiiteRussian - 1 month ago 7
Javascript Question

RegEx trying to match anything but a certain pattern with chars from the pattern being allowed

In this case I am trying to create a pattern that matches anything BUT a

|
or
}}
but I would like to understand how to do this in the general case as well.

That is I would like to match any character any number of times and stop once I hit either a
|
or a
}}

So

[\w\s`~!@#\$%\^&\*\(\)-\+=\[\]\\;"',<\.>\/\?\{\}:]*


and return when I hit
}}
or
|


What I currently have is:

var regex = /[\w\s`~!@#\$%\^&\*\(\)-\+\=\[\]\\;"',<\.>\/\?\{\}\:]*(?!((\|)|(\}\})))/


then something like

var str = "abc}}";
str.match(regex)


should return
abc
but mine doesn't even work even after hours using debuggex

The problem I have is I need to also be allowed to have a single
}
within my match so just taking out the
\}
from the first group doesn't work.
I don't even understand how this is possible and in other expressions I will need to be able to recognize
[anything but {{, {:, {{{, |, }}]
and I can't grasp the logic to code this.
Also in case I missed a special character that needs to be escaped or have a redundant backslash please let me know.

Answer

Maybe something like this:

/(.+?)(\||}}||$)/

That is:

  • (.+?) non-greedy capturing match of one or more of any character
  • (\||}}||$) capturing match of \| or }} or $ (end of string).

The result you want will be the first captured match, i.e., the second item of the array returned by .match() (if there is a match):

var regex = /(.+?)(\||\}\}|$)/;
console.log("abc}}".match(regex));
console.log("abc}def}}".match(regex));
console.log("abc}123}456}}x".match(regex));
console.log("abc|def".match(regex));
console.log("abc".match(regex));