开发者

Match any word but two in specific

I'm trying to create a regular expresion to match any word ( \w+ ) except true or false.

This is what I got so far is: \w+\s*=\s*[^true|^false]\w+

class Ntnf { 
 public static void main ( String ... args ) { 
  System.out.println( args[0].matches("\\w+\\s*=\\s*[^true|^false]\\w+") );
 }
}

But is not working for:

a = b
a = true
a = false

It matches always.

How can I match any word ( \w+ ) except true or false?

EDIT

I'm tryi开发者_运维百科ng to spot this pattern:

a = b
x = y
name = someothername
etc = xyz
x = truea
n = falsea

But avoid matching

a = true
etc = false
name = true


You can use:

^(?!(true|false)$)
  • ^ - beginning of string
  • ?! - negative lookahead
  • $ - end of string

So it matches as long as the whole string isn't just "true" or "false". Note that it can still start with one of those.

However, it may be more straightforward to use regular string comparisons.

EDIT:

The whole regex (without escaping) for your situation is:

^\w+\s*=\s*(?!(true|false)$)\w+$

It's the same idea, except that we're putting it in the equation form.


[^true] Is a character class. It only matches one character. [^true] means: "Match this character only if it not one of t, r, u or e". This is not what you need, right?

Regex is not a good idea for this task. It will be quite complicated to do it in regex. Just use string comparison.


Square brackets match a list of possible characters, or reject a list of possible characters (not necessarily in the order you specify), so [^true] is not the way to go.

When I'm trying not to match a certain word, I usually do the following: ([^t]|t[^r]|tr[^u]|tru[^e])

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜