Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a regex for capturing one symbol only, but with restrictions?

I need a regex for javascript that allows me to select a single character with a restriction: that it does NOT have a specified character besides itself.

I need to select the character / but only if it does NOT have the character a besides it.

E.g.:

str = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t";

myregex = ????
var patt = new RegExp(myregex);
var res = patt.split(str);

And the result should be something like this:

res[0] = "I Like this"
res[1] = " and a/ basketball is round a/a ups.Papa/ tol"
res[2] = "d "
res[3] = "me tha/t"

The regex should be something like: (if a then not)(\/)(if a then not)

I have no idea how to do it, I tried: [^a](\/)[^a], but then it selects also the characters that are beside the /, like s/, l/d, not the a's; I don't want to select the characters beside the /.

like image 211
babo221 Avatar asked Jan 18 '18 11:01

babo221


1 Answers

Split by /(?<!a)\//g

var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/(?<!a)\//g);
console.log(output);

Explanation

  • /(?<!a)\/ matches / which is not preceded by a

Note

  • Works on chrome, doesn't work on FF as suggested by @SoulReaver in his comments.

Edit

Or alternatively, you can just split by /

var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/\//g);
output = output.reduce( function(a,c){
  var lastItem = a.slice(-1)[0];
  //console.log(lastItem)
  if ( lastItem && lastItem.slice(-1) == "a" )
  {
     a.pop();
     a.push(lastItem.concat("/").concat(c));
  }
  else
  {
     a.push(c);
  }
  return a;
}, [])
console.log(output);

Edit 2

If a has to be ignored on either sides of /, then use the previous answer (based on reduce), just add the look-ahead in split

var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/\/(?!=a)/g);
like image 80
gurvinder372 Avatar answered Sep 22 '22 10:09

gurvinder372