简体   繁体   English

如果正则表达式不包含特定单词,如何匹配它?

[英]How match a regex if it does not contain a particular word?

I want to write a regex in Python or JavaScript to match if the given string does not JUST contain the given word (eg "any").如果给定的字符串不只包含给定的单词(例如“任何”),我想在 Python 或 JavaScript 中编写一个正则表达式来匹配。

For example:例如:

any : does not match any :不匹配
AnY : does not match AnY : 不匹配
anyday : match anyday :比赛
any day : match any day :比赛
blabla : match blabla : 匹配

If you also need words other that starting with "any" you can use a negative lookahead如果您还需要以“any”开头的单词,则可以使用否定前瞻

^(?!any$).*$

This will match anything besides "any".这将匹配除“any”之外的任何内容。

It is probably more efficient to not use a regex, this works as well:不使用正则表达式可能更有效,这也有效:

def noAny(i):
    i = i.lower().replace('any', '')
    return len(i) > 0

Something like this:像这样的东西:

/(any)(.+)/i
any.+

..and some text to make the 30char threshold ..和一些文字来制作 30char 阈值

Use string.match(regexp) method in javascript for this purpose.为此,在 javascript 中使用string.match(regexp)方法。 See the code below:请看下面的代码:

<script type="text/javascript">
      var str="source string contains YourWord"; 
      var patt1=/YourWord/gi; // replace YourWord within this regex with the word you want to check.  
      if(str.match(patt1))
      {
         //This means there is "YourWord" in the source string str. Do the required logic accordingly.
      }
      else
      {
          // no match
      }
</script>

Hope this helps...希望这可以帮助...

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

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