Özgür Utku
Özgür Utku

Reputation: 57

java regex not operator not working properly

(\d+(\.|\,|\\|\/|\-)\d+) I have a regex like this. I'm catching numbers like 15.12, 15/15 with this regex it works correctly. But when I get the inverse with the not operator, it doesn't exactly work properly. Regex with "not" operator. [^(\d+(\.|\,|\\|\/|\-)\d+)]

Let's take "15/12 tons/tonne" as the sample text. Here I expect it to find ton/ton, but it doesn't take the "/" character, it just takes tonton. What am I doing wrong ? How can I fix ?


Example;

15/13 48 km/h  ---> 48 km/h

13.12 ton.     ---> ton.

10,11 ,kwh     ---> ,kwh

9-7 .mm.       ---> .mm.

As seen in the example, I want to find everything except numbers(including whitespaces).

Upvotes: 0

Views: 251

Answers (1)

user12842282
user12842282

Reputation:

[^(\d+(\.|\,|\\|\/|\-)\d+)] is not the inverse of (\d+(\.|\,|\\|\/|\-)\d+)

In regular expressions, anything between the brackets are considered a character set. The ^ is a special character when it's the first character in the set, with it meaning the inverse of the character set.

https://regex101.com/r/7gJANc/4

This is a good way to see exactly which characters are being matched (or not matched) by that pattern.

Last edit:

To find what you're looking for, you can invert each of the instances of \d to \D. \D means "not-digit".

(\D+(\.|\,|\\|\/|\-)\D+) is your pattern but with \D:

https://regex101.com/r/7gJANc/5

It matches tons/tonne

Upvotes: 1

Related Questions