问题
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