0

I want to split string for ">" but not when >> in JavaScript.

But once I am doing a split const words = str.split('>'); it is splitting >> as well.

Currently, after the split I look for "> >" and then substitute them with ">>".

How to implement it properly.

4
  • 1
    Removed python from title, since the question talks about and is tagged javascript. Commented Mar 16, 2022 at 16:58
  • 1
    Split on a regex? str.split(/>(?!>)/g) This will still split on the second of the two >s though. Commented Mar 16, 2022 at 16:59
  • Can you post the example string and expected output? Commented Mar 16, 2022 at 17:07
  • Does this help: console.log('a>b>>c>d>>e>f;'.replaceAll('>>', '^^^').split('>').map(x => x.replace('^^^', '>>'))); (NOTE: You may use a different temporary replacement-placeholder insteadof '^^^') Commented Mar 16, 2022 at 17:35

1 Answer 1

1

You can use a regular expression leveraging:

  • Negative lookbehind (?>!) causing a group to not be considered when the pattern matches before the main expression
  • Negative lookahead (?!) causing a group to not be considered when the pattern matches after the main expression

The resulting pattern would be as follows:

/(?<!>)>(?!>)/

Using the patter to tokenize an input would lead the desired results:

"here>>I>am".split(/(?<!>)>(?!>)/) // => [ 'here>>I', 'am' ]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.