Regex AND operator for overlapping matches

Deadly 提交于 2021-01-28 07:07:01

问题


I have two strings that are varying lengths of my name

chriscattano
christiancattano

I have substrings in lengths of 3 through 10 that both strings share

(chr)(hri)(ris)(cat)(att)(tta)(tan)(ano)(chri)(hris)(catt)(atta)(ttan)(tano)(chris)(catta)(attan)(ttano)(cattan)(attano)(cattano)

I am trying to put these into a regex search that will successfully match the words chris and cattano so that I can do a .replace, and apply a <span> with a sass class to the match's results.

If I format my regex to be:

/(chr)|(hri)|(ris)|(cat)|(att)|(tta)|(tan)|(ano)|(chri)|(hris)|(catt)|(atta)|(ttan)|(tano)|(chris)|(catta)|(attan)|(ttano)|(cattan)|(attano)|(cattano)/g

I manage to mutually match on chr and cattan, but I cannot figure out how to highlight chris and cattano; I'm missing the is and the o.

This example can change drastically as I am only using my name to test and perfect the functionality. It will eventually be used on email addresses, names, and addresses. So changing the order of the capture groups (if that could fix this) is not a solution and when it made to be more dynamic I will have little control over the order of the captures groups when they're put into a regex object, and fed as a parameter to the .replace() method.

Here is a regexpal where I've been trying various things to get it to highlight the matches I need. Hopefully someone might be able to tinker it into working?

http://www.regexpal.com/?fam=97413


回答1:


You need to sort the items in your array by length in the descending order to make sure the longest alternatives are tested first, and then join them into a pattern with .join("|").

That is because in an NFA regex like JS or most others the first alternative found makes the regex engine stop processing the group. You may read more about it in Remember That The Regex Engine Is Eager.



来源:https://stackoverflow.com/questions/43454690/regex-and-operator-for-overlapping-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!