user2144555
user2144555

Reputation: 1313

Regex - Negate a specific string / sequence of numbers [java]

I'm having problems finding a RegEx that negates a specific String. In this case, I'm dealing with numbers.

If I want to exclude the number '12' of my group of numbers:

[1, 12, 121, 212, 312]

How can I do it by using a RegEx? If I use something like ^((?!12).)*$, it will exclude all the numbers except the "1", because all of them have the '12' pattern.

What would be the rigth expression to use in this case?

Upvotes: 3

Views: 162

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174706

You could simply use this,

^(?!.*\\b12\\b)\\d+$

Negative lookahead at the start asserts that there isn't a number 12 preceded and followed by a word boundary in the strings which are going to match.

Upvotes: 0

Maroun
Maroun

Reputation: 95968

You don't really need regex for this, you can simply:

String num = "[1, 12, 121, 212, 312]".split(",")[1].trim();

Upvotes: 0

vks
vks

Reputation: 67968

^((?!\b12\b).)*$

This should do it for you.Word boundaries will enable you to exclude just 12 and not others.

Upvotes: 4

Related Questions