panipsilos
panipsilos

Reputation: 2209

Regex that negates a whole word

I have the following scenario where I need to extract the RAM value from string like the following:

1GB, 4GB ROM Android 5.1 3G

The RAM value is 1GB

Currenlty , I m using the following regex:

(\d+(?:\.\d+)?)\s?([Gg])[Bb]

However, in this case I also get the 4GB value which corresponds to the ROM value. How can I write the regex so that it doesnt match when the ROM word follows?

Thank you

Upvotes: 1

Views: 115

Answers (2)

Thomas Ayoub
Thomas Ayoub

Reputation: 29471

You can use the following negative lookahead:

(?i)\d+Gb(?!\s*ROM)

It will match digits followed by Gb but not ROM

Upvotes: 1

fabian
fabian

Reputation: 82511

Use a negative lookahead

(\d+(?:\.\d+)?)\s?([Gg])[Bb](?!\s?[Rr][Oo][Mm])

The (?!\s?[Rr][Oo][Mm]) part means the following string must not match \s?[Rr][Oo][Mm].

You may want to consider using the Pattern.CASE_INSENSITIVE flag instead of the character groups, btw.

Upvotes: 5

Related Questions