Java RegEx匹配任何内容但是文字字符串'NIL'或'nil' [英] Java RegEx that matches anything BUT literal string 'NIL' or 'nil'

查看:167
本文介绍了Java RegEx匹配任何内容但是文字字符串'NIL'或'nil'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,伙计们。这是一个Java面试类型的问题,似乎已经让一些非常聪明的人难过了。他们实际上需要这个用于生产代码,因此它不仅仅是一个采访益智游戏。



他们需要一个Java中的正则表达式,如果字符串文字是任何除了3个字母的单词NIL之外。测试需要不区分大小写,RegEx本身必须完成所有工作。



因此,RegEx应该拒绝 NIL,nil,NiL,nIL, ,等等。



但是,它应该接受:nile,anil,will,zappa-nil-a和空字符串。



编写一个简单的RegEx需要多少Java开发人员?显然很多!

解决方案

您可以使用负向前瞻



启用不区分大小写的选项:

  ^(?!nil $)。* 

如果你不需要在匹配中真正返回字符串,你可以在最后留下。* 。这是一个没有不区分大小写选项的版本:

  ^(?![nN] [iI] [lL] $) 。* 

说明:

  ^#字符串锚点开始
(?!#start negative lookahead(如果...则失败)
nil#literal characters'nil'
$#end of string
)#end look lookahead
。*#consume string(不是必需的,但它更像是典型的正则表达式)

如果您希望正则表达式匹配 nil \ n ,请使用 \ z 而不是 $ ^(?!nil \ z)。*


OK, guys. Here's a Java interview-type question that seems to have stumped some very smart people around here. They actually need this for production code, so it's more than just an interview puzzler.

They need a regular expression, in Java, that returns true if a string literal is anything other than the 3-letter word NIL. The test needs to be case insensitive, and the RegEx itself must do all the work.

So, the RegEx should reject NIL, nil, NiL, nIL, and so on.

It should, however, accept: nile, anil, will, zappa-nil-a, and the empty string.

How many Java developers does it take to write a trivial RegEx? Apparently a lot!

解决方案

You can do this using a negative lookahead.

With case-insensitive option enabled:

^(?!nil$).*

You could leave off the .* at the end if you don't need to actually return the string in the match. Here is a version without the case-insensitive option:

^(?![nN][iI][lL]$).*

Explanation:

^       # start of string anchor
(?!     # start negative lookahead (fail if...)
   nil    # literal characters 'nil'
   $      # end of string
)       # end lookahead
.*      # consume string (not necessary, but it acts more like a typical regex)

If you want the regex to match nil\n, then use \z instead of $ in the lookahead: ^(?!nil\z).*

这篇关于Java RegEx匹配任何内容但是文字字符串'NIL'或'nil'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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