Element Green
Element Green

Reputation: 442

Python regex search for decimal digits not followed by character

Using re.search to find one or more decimal digits, an optional K character, not followed by a '%'.

Tried this:

re.search (r'(\d+K?)(?!%)', s).group (0)

With the following values for s:

10K 1%
2% 10K
20% 10K

Which returns:

10K
10K
2

The first two results are correct, the last one is not. I want the digit matching to be greedy and skip the "20%" and match the "10K" instead. Found a solution for Java (++), but not Python. Thanks for any tips on this, searched online extensively, but answer has been elusive.

Upvotes: 2

Views: 174

Answers (2)

Nambi_0915
Nambi_0915

Reputation: 1091

Try regex \d+K?(?= |$)

This will check a space or an End of the line after K.

Regex

Upvotes: 1

lucas_lyfu
lucas_lyfu

Reputation: 41

? mean match 0 or 1 time, replace pattern to (\d+K)(?!%)

Upvotes: 0

Related Questions