Sid
Sid

Reputation: 552

Match Integer and float with only single or 2 digits in python regex

I dealing with a string that consists of integers and float values and also other numeric stuff. I am interested to pick up only 1 or 2 digits integer or float numbers using regex in python. The digits of my interest could be at the start of the string in between the string at the end of the string

A sample string is given below

1 2 years of experience in dealing with 20-20-20 and python3 and 5 development and maintenance of 500.

I am interested in 1,2 and 5. And not in 500 or 20-20-20

The regex I am trying is

((?:^|\s)\d{1,2}\.\d{1,2}(?:$|\s))|((?:^|\s)\d{1,2}(?:$|\s))

but it doesn't detect 2 and 5. Any help is appreciated.

Upvotes: 0

Views: 274

Answers (1)

user7571182
user7571182

Reputation:

You may try:

(?:^| )([+-]?\d{1,2}(?:\.\d+)?)(?= |$)

Explanation of the above regex:

  • (?:^| ) - Represents a non-capturing group matching either the start of line or a space.
  • ([+-]?\d{1,2}(?:\.\d+)?) - Represents first capturing group capturing all the one or 2 digit floating numbers(negative or positive). If you want to restrict the decimal digits; you can make your required changes here. Something like ([+-]?\d{1,2}(?:\.\d{DESIRED_LIMIT})?).
  • (?= |$) - Represents a positive look-ahead matching the numbers which are either followed by a space or represents end of the line.

Pictorial Representation

You can find the demo of the above regex in here.

Sample implementation in python:

import re

regex = r"(?:^| )([+-]?\d{1,2}(?:\.\d+)?)(?= |$)"
# If you require for number between 0 to 20. (?:^| )([+-]?(?:[0-1]?\d|20)(?:\.\d+)?)(?=\s|$)

test_str = "1 2 years of experience in dealing with 20-20-20 and python3 and 5 development and maintenance of 500. -2 is the thing. 20.566"

print(re.findall(regex, test_str, re.MULTILINE))
# outputs: ['1', '2', '5', '-2', '20.566']

You can find the sample run of the above implementation in here.

Upvotes: 3

Related Questions