简体   繁体   English

正则表达式:找出符号是否被等号包围

[英]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. 我需要一个JS正则表达式,它将找到不被任何相等的单词字符包围的单词字符的匹配项。 For example, if we are looking for b it should match aba or ubu and should not abc or bca . 例如,如果我们正在寻找B检查应与ABAUBU和不应该ABCBCA。

Any characters in the given string are lowercase English letters, which are alternate (eg we can have ababa but cannot bbaa ). 给定字符串中的所有字符都小写英文字母,它们是交替的(例如,我们可以有贝巴 ,但不能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 . 但是我没有设法弄清楚如何替换a,以便我们知道它与b左右两侧的符号相同。 Any insights are appreciated. 任何见解都表示赞赏。

Using below regex: 使用以下正则表达式:

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

You are able to match these kind of characters. 您可以匹配这些字符。 If you need to manipulate surrounded b s then you can code it like this: 如果需要操纵包围的b则可以这样编写:

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

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" 然后,如果您想获取所有隔行扫描模式,例如"abaubuiyiatbzsgegestsabn" ,则不仅应获取"geg" ,还应获取"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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM