Igor Skoldin
Igor Skoldin

Reputation: 750

Regex: find out if the symbol is surrounded with equal symbols

I need a JS regex that will find matches of a word character that are not surrounded by any equal word characters. For example, if we are looking for b it should match aba or ubu and should not abc or bca.

Any characters in the given string are lowercase English letters, which are alternate (e.g. we can have ababa but cannot bbaa).

I tried using lookarounds like this:

/b(?=a)/g

But I did not manage to figure out how do I replace the a so that we know that it is the same symbol that is on the left and the right side of b. Any insights are appreciated.

Upvotes: 0

Views: 578

Answers (2)

Redu
Redu

Reputation: 26161

You might do as follows;

var found = "abaubuiyiatbzsgegestsabn".match(/(\w)[^\1]\1/g);
console.log(found);

Then if you would like to get all interlaced patterns such is in "abaubuiyiatbzsgegestsabn" you should not only get "geg" but also "ege"

var str = "abaubuiyiatbzsgegestsabn".split(/(\w)(?=[^\1]\1)/g)
                                    .slice(1)
                                    .reduce((p,c,i,a) => i&1 ? (p[p.length-1] += (a.slice(i)
                                                                                   .join("")
                                                                                   .slice(0,2)),p) : p.concat([[c]]) ,[]);
console.log(str);

Upvotes: 0

revo
revo

Reputation: 48721

Using below regex:

(.)(b)(?=\1)

You are able to match these kind of characters. If you need to manipulate surrounded bs then you can code it like this:

> "aabb aba".replace(/(.)(b)(?=\1)/g, function(match, p1, p2) {
    return p1 + 'c';
});
< "aabb aca"

Upvotes: 2

Related Questions