i have string like this
{wrongTag}} RegExr was {{created}aaaa{{fffffff}} shks {{sdfsdfsd} and {{created}aaaa{{fffffff}
i want to remove all wrong tags either single bracket is missing from the start or end of tag. in example about only {{fffffff}} is correct tag all other tags are worng should be removed , my code is this for removing all wrong tags
const cleanString = message.replace(/(?!{{[^{{}}] \}\})\{{[^{{}}] \}/g, "")
but my regex is only detecting last missing baraket . So following wrong tag also be matched
{wrongTag}}
{missingtag}
Below is my Regex , you can see its working partially but not fully any help would be appricated
CodePudding user response:
You can use
const cleanString = message.replace(/(?<!{)({{[^{}] }})(?!})|{ [^{}]*} /g, '$1');
Or,
const cleanString = message.replace(/((?:[^{]|^){{[^{}] }})(?!})|{ [^{}]*} /g, '$1');
See the regex demo #1 / regex demo #2. The point is to match and capture into Group 1 any valid tag, and then match and remove the tags with any one or more curly braces around them.
Details:
(?<!{)- a negative lookbehind that fails the match if there is a{char immediately to the left of the current location({{[^{}] }})- Group 1:{{, one or more chars other than{and}, and then}}(?!})- a negative lookahead that fails the match if there is a}char immediately to the right of the current location|- or{- one or more{chars[^{}]*- zero or more chars other than{and}}- one or more}chars.
In the no-lookbehind solution, (?<!{) is replaced with (?:[^{]|^) that matches either a char other than { (with [^{]) or start of string (with ^).
CodePudding user response:
If you're looking for mismatched brackets, you could use the following test for missing leading brackets
[^{]{([^{}] )\}\}
and this for missing trailing brackets
{{([^{}] )\}[^}]
and this for missing leading and trailing brackets
[^{]{([^{}] )\}[^}]
It can by done with a single regex; but you're well on your way to write only code when you try to make a regular expression do more than a single operation at a time.
In plain english; the first expression would read: Find the first '{' that is not preceded by a '{'. Match a group of characters that do not contain '{' or '}' until you reach a '}' followed by another '}'
The second is basically the same statement, but it reads: Find the first "{{". Match a group of characters that do not contain '{' or '}' and consider it a match if the next '}' is not followed by '}'.
The third is just a combination of the first two, to match items that are wrapped in "{}" but not in "{{}}"
