[英]How to get the last occurrence of a word from a list of possible words using Javascript regex?
I need to test if an address contains a particular placename from a list of placenames. 我需要测试地址是否包含地名列表中的特定地名。 For example, if I have an address that looks like 123 someplace, someStreet, dublin
then the following regex (dublin|cork|galway)
will give me county dublin
. 例如,如果我的某个地址看起来像123 someplace, someStreet, dublin
那么下面的正则表达式(dublin|cork|galway)
将给我dublin
县。
The problem is if dublin
was to appear in some other portion of the address eg 123 someplace, dublin road, cork
then I'll still get dublin
but I actually want cork
. 问题是,如果dublin
会出现在地址的其他部分,例如123 someplace, dublin road, cork
那么我仍然会得到dublin
但我实际上想要cork
。
Is it possible to write a regex to get the last occurrence, if any, of a list of possible match words. 是否有可能编写一个正则表达式来获取可能出现的匹配词列表的最后一次出现(如果有的话)。 I see that C# regexes have a right-to-left option, that would be great but I don't think Javascript has anything like that, does it? 我看到C#正则表达式具有从右到左的选项,这很好,但是我不认为Javascript具有这样的功能,对吗?
Note that I can't rely on the formatting of the address, so there might not be commas delimiting the string. 请注意,我不能依赖地址的格式,因此可能不会用逗号分隔字符串。 Also, although it is very likely that the word I'm looking for is the very last word in the string, this might not always be the case. 同样,尽管我要查找的词很可能是字符串中的最后一个词,但情况并非总是如此。
You can use positive look ahead 您可以使用正面的展望
(dublin|cork|galway)(?!.*(dublin|cork|galway))
matches the last occurence 匹配最后一次出现
see how the regex works 看看正则表达式如何工作
http://regex101.com/r/yQ6bY1/2 http://regex101.com/r/yQ6bY1/2
(?!.*(dublin|cork|galway))
asserts that the pattern cannot be matched after the presceding pattern, (dublin|cork|galway) (?!.*(dublin|cork|galway))
断言在前面的模式(dublin | cork | galway)之后,该模式无法匹配
OR 要么
To be more precise, 更准确地说,
\b(dublin|cork|galway)\b(?!.*\b(dublin|cork|galway)\b)
Thanks to nhahtdh for the suggestion. 感谢nhahtdh的建议。
Find desired string and check that end of line does not contain it. 找到所需的字符串并检查行尾是否不包含该字符串。
(dublin|cork|galway)(?!.*(dublin|cork|galway))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.