Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify integer, string and floating point literals

Tags:

python

regex

I am new to Python and I am stuck with a problem. I have an input file which contains data as below:

12345    67890     afghe
abcde    23456     0abcd
34567    __fred01  45678
123.456  12345a    123.
.456     ab00cd    00ab00

By using regular expression is need to parse each literal and classify whether the literal is a string or an integer or a floating point. The code snippet is somewhat like below:

def processtoken(token):
    #Replace the following line with your code to classify
    # the string in 'token' according to your three Regular
    # Expressions and print the appropriate message.
    print('Inside Process Token')

    match = re.search(r'(0|[1-9][0-9]*|0[oO]?[0-7]+|0[xX][0-9a-fA-F]+|0[bB][01]+)[lL]?', token)
    matchfp = re.search(r'^[0-9]+\.?[0-9]+$',token)
    if match:
        print(match.group(),'matches INT')
    elif matchfp:
        print(matchfp.group(),'matches FP')

My issue is how can I structure the code to validate multiple regex conditions for each token passed. As of now the floating point if the condition is not validated. I want to check the token for, first integer regex if it matches or if it matches floating point regex or it matches string. Any help will be appreciated.

like image 871
np05 Avatar asked Aug 29 '26 07:08

np05


1 Answers

I would structure the problem as follows:

integer_regex = r"^...$"
float_regex = r"^...$"
string_regex = r"^...$"

def processToken(token):

    if re.search(integer_regex, token):
        print(token, 'matches INT')
    elif re.search(float_regex, token):
        print(token, 'matches FLOAT')
    elif re.search(string_regex, token):
        print(token, 'matches STR')
    else:
        print(token, 'unknown')

Filling your patterns into the *_regex variables above.

Also note, your float pattern is no good, as it also matches int:

r'^[0-9]+\.?[0-9]+$'

Since the decimal point is optional. You might be better off breaking the pattern into an alternation with three options, starts with '.', ends with '.' or contains a '.' between numbers. Also, in your integer pattern, the '?' in the octal section is incorrect:

0[oO]?[0-7]+

at this point we're trying to commit to octal so the prefix is not optional:

0[oO][0-7]+

You got this correct for hex and binary.

like image 189
cdlane Avatar answered Aug 31 '26 21:08

cdlane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!