128k views
1 vote
Write a regular expression that matches positive real numbers starting and ending with a digit and possibly including a decimal point – for example, 0.0035, 1.94, or 47 . There should be no leading zero in the case of numbers >=1, and there should be a single leading zero for numbers less than one. Your regular expression should use concatenation, + for alternation ("or"), and * for closure ("zero or more.") You may also use "[0-9]" for a single digit.

1 Answer

4 votes

Answer:

#section 1

import re

pattern = r'^(\d+)(\.?)(\d+)$'

pattern2 = r'(^0+)(\d+)$'

pattern3 = r'^(0)(\.)(\d+)$'

tex = '0.0035 is coming 1.94 hopefully 47 home 000657 with 00.543'

print(a)

tex = tex.split()

ls = []

#section 2

for i in tex:

if re.match(pattern, i):

if float(i) < 1 and re.match(pattern3, i):

ls.append(i)

elif float(i) >= 1 and not re.match(pattern2, i):

ls.append(i)

print(ls)

Step-by-step explanation:

The programming language used is python 3.

#section 1

This is a regular expression question and the first thing to do will be to import the regular expression module.

The regular expression patterns are then created

pattern = r'^(\d+)(\.?)(\d+)$' This pattern traps all digits integers of decimals

pattern2 = r'(^0+)(\d+)$' This pattern traps all digits without a decimal point that have a leading zero(0)

pattern3 = r'^(0)(\.)(\d+)$' This pattern traps all digits that are less than one and have a decimal point and just one zero(0) in front of the decimal.

REGULAR EXPRESSION TIPS:

^ means starts with

$ means ends with

+ means one or more occurrences

? means zero or one occurrences

\d represents digits from 0-9 you can also use [0-9]

\ is used to escape special characters.

() represents a group

note: the dot(.) is a special character in other to include it we must escape it

with this tips you will be able to understand the patterns.

A string containing some digits is passed to the tex variable to test the code.

The string is split up into a list using the split() method and an empty list is created to hold the result.

#section 2

I make use of for loops and if statements to compare each item in the list to each of the patterns.

In simple words, for each element in the list, if that element matches pattern1 , it is a number.

The code moves to the next if statement to check if it's less than 1 and checks the leading zeros to ensure it is only 1, if it agrees with all the conditions, it is added to the new list.

if it does not, it goes to the elif statement to check if it is greater or equal to 1 and has no leading zeros. if that happens to be true. it is also added to the new list.

Finally, the result is printed to the screen.

check the picture to see code at work.

Write a regular expression that matches positive real numbers starting and ending-example-1
User Thatismatt
by
5.6k points