CodexBloom - Programming Q&A Platform

Regex scenarios to Capture Custom Delimited Strings in JavaScript - implementing Escaped Characters

👀 Views: 387 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
regex javascript node.js JavaScript

I'm converting an old project and I'm trying to parse a string that contains custom delimited entries, specifically using a pipe (`|`) as the delimiter, but I need to account for instances where the pipe is escaped using a backslash (`\`). For example, given the input `"value1|value2|value\|with|escaped|pipe"`, I want to capture each value while treating `value\|with` as a single entry. I've been trying to use the following regex pattern: ```javascript const input = 'value1|value2|value\\|with|escaped|pipe'; const regex = /(?<!\\)(\|)(?!(?:(?:\\\\)*)\|)/g; const parts = input.split(regex); console.log(parts); ``` However, this is not working as expected. The regex seems to ignore the escape character, and I'm getting an array that includes the unescaped pipe as separate entries. Instead of the desired output `['value1', 'value2', 'value\|with', 'escaped', 'pipe']`, I'm getting `['value1', 'value2', 'value', 'with', 'escaped', 'pipe']`. I've tried debugging by simplifying the regex and testing different escape sequences but it still fails to correctly handle the escaped pipes. I'm using Node.js v14.x for this implementation. Any suggestions on how to properly capture these delimited strings with escaped characters would be greatly appreciated! What am I doing wrong?