1

I have this regex:

/(\[.*?\])/g 

Now I want to change that regex to matches everything except current-matches. How can I do that?

For example:

Current regex:

 here is some text [anything123][/21something] and here is too [sometext][/afewtext] and here // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ 

I want this:

 here is some text [anything123][/21something] and here is too [sometext][/afewtext] and here // ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ ^^^^^^^^^ 
5
  • 2
    Just use replace to replace the matches. str.replace(/(\[.*?\])/g, '') Commented Feb 28, 2016 at 12:57
  • @Tushar I want to know is there any approach to match everything except pattern in regex? Commented Feb 28, 2016 at 12:58
  • I would follow Tushar's suggestion using replace, that's what I was going to say. Commented Feb 28, 2016 at 13:09
  • 1
  • text.split(/\[.*?\]/g) Commented Feb 28, 2016 at 13:37

1 Answer 1

2

Match what's inside or capture what's outside the trick

\[.*?\]|([^[]+) 

See demo at regex101

Demo:

var str = 'here is some text [anything123][/21something] and here is too [sometext][/afewtext] and here'; var regex = /\[.*?\]|([^[]+)/g; var res = ''; // Do this until there is a match while(m = regex.exec(str)) { // If first captured group present if(m[1]) { // Append match to the result string res += m[1]; } } console.log(res); document.body.innerHTML = res; // For DEMO purpose only

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

5 Comments

@stack This does the same thing. You just need to get the first captured group and join them.
@Tushar Yeah I know the content of $1 is exactly what I need. btw, I can do that exactly as you said (using .replace()), But to be honest, I want to know how can I do that using lookahead (?!)? (Because I saw an approach using lookahead somewhere)
@Tushar Thank you .. yes it works ... But I think I cannot tell you what I want exactly .. :-) !! All I want to know is: how do I define a regex to matches everthing except its pattern (pure regex)
@stack you want this but this does not work in JS regex :p
@stack Because that are PCRE verbs. You could try like this with lookaheads but this is expensive and more prown to fail.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.