1

I would like to split a string where the delimiter is a pipe. But the pipe can be escaped and not splitted than.

example:

'aa|bb|cc'.split(/*??*/) // ['aa','bb','cc']
'aa\|aa|bb|cc|dd\|dd|ee'.split(/*??*/) // ['aa|aa', 'bb', 'cc', 'dd|dd', 'ee']

I try this, but it not work in javascript: (?<!\\)[\|]

2
  • Go with match. Commented Jan 26, 2018 at 21:31
  • how to do that? Commented Jan 26, 2018 at 21:34

3 Answers 3

2

Try this:

    console.log('aa|bb|cc'.split('|'));
    console.log('aa\|aa|bb|cc|dd\|dd|ee'.split('|'));

Sign up to request clarification or add additional context in comments.

4 Comments

var result = 'aa\|aa|bb|cc|dd\|dd|ee'.split('|');
it not work. I want this ['aa|aa', 'bb', 'cc', 'dd|dd', 'ee'] and I get this: ["aa", "aa", "bb", "cc", "dd", "dd", "ee"]
@Rajaswami: and how could we possibly know what you were expecting? Did you include the desired result with your question?
Yes he did. Just look at code comments and read question more carefully.
2

I assume that you want to skip splitting on escaped pipes. Use match instead:

console.log(
  'aa\\|aa|bb|cc|dd\\|dd|ee'.match(/[^\\|]*(?:\\.[^\\|]*)*/g).filter(Boolean)
);

Comments

0

Hi the Regex I created

https://www.regexpal.com/index.php?fam=100132

What you need to do is concact the matches in an array

the code generated looks like this...

const regex = /(([^\\\|]+)\\?\|\2)|(\w+)/g;
const str = `aa\\|aa|bb|cc|dd\\|dd|ee`;
let m;

while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
    regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
    console.log(`Found match, group ${groupIndex}: ${match}`);
});

}

Hope this help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.