正则表达式,除了特定的单词 [英] Regex with exception of particular words

查看:152
本文介绍了正则表达式,除了特定的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有正则表达式的问题。
我需要使用正则表达式来排除一组指定的单词,例如:apple,orange,juice。
并给出这些单词,它将匹配除上述单词之外的所有内容。

 苹果(不应该匹配)
applejuice(match)
yummyjuice(match)
美味苹果汁(搭配)
orangeapplejuice(匹配)
橙色(不应该匹配)
果汁(不应该匹配)
橙苹果汁(匹配)
apple-orange-aple(match)
果汁汁(匹配)
橙汁(匹配)


解决方案

如果你真的想用一个正则表达式来做到这一点,你可能会发现有帮助(尤其是在这个例子中是负面的)。为Ruby编写的正则表达式(某些实现具有不同的查找语法):

  rx = / ^(?!apple $ | orange $ |果汁$)/ 


I have problem with regex. I need to make regex with an exception of a set of specified words, for example: apple, orange, juice. and given these words, it will match everything except those words above.

apple (should not match)
applejuice (match)
yummyjuice (match)
yummy-apple-juice (match)
orangeapplejuice (match)
orange (should not match)
juice (should not match)
orange-apple-juice (match)
apple-orange-aple (match)
juice-juice-juice (match)
orange-juice (match)

解决方案

If you really want to do this with a single regular expression, you might find lookaround helpful (especially negative lookahead in this example). Regex written for Ruby (some implementations have different syntax for lookarounds):

rx = /^(?!apple$|orange$|juice$)/

这篇关于正则表达式,除了特定的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆